Comparing Arrays (with.Java)
This article introduces bubble sorting.
In preparation for a coding test, I’ve been studying algorithms, and in this article, I’d like to summarize the bubble sort.
What is bubble sort?
Bubble sorting is an algorithm that compares two adjacent elements, shifting smaller values to the left.
Understanding Bubble Sort
Initial array: [5, 2, 9, 1, 5, 6]
First pass: [2, 5, 1, 5, 6, 9].
- Compare and swap the first and second elements. The 5 is exchanged for the 2.
- Next, compare and exchange the second and third elements. The 5 is exchanged for the 9.
- This process continues until the largest element is moved to the far right.
- At the end of this pass, the largest element is aligned to the far right.
Second pass: [2, 1, 5, 5, 6, 9].
- Again, starting with the first, the first and second elements are compared and swapped. This time, the 2 and 5 are not exchanged.
- Compare and exchange the second and third elements. The 5 and 1 are exchanged.
- This process is repeated until the second largest element is sorted in front of the one from the far right.
Final sorted array: [1, 2, 5, 5, 6, 9].
- Repeat the above process, performing passes the length of the array.
- In each pass, the largest value is moved to the far right, so the unaligned portion decreases as the passes progress.
See
This is how bubble sorting works, starting with the largest value in the array and moving it to the right in turn. The efficiency of this algorithm is poor, so it’s not recommended for large arrays.