Java bubble sort code

Java Bubble Sort code in ascending order

Bubble sort is one of the most popular sorting algorithms. It compares pairs of adjacent elements and swaps each other until they are all ordered. The largest element raises or bubbles to the top of the array.
This is the bubble sort code to sort an array of integers in ascending order.
public static void bubbleSort(int[] A) {
       int i, j, swap;
       for (i = 0; i < A.length - 1; i++) {
            for (j = 0; j < A.length - i - 1; j++) {                                                              
                 if (A[j + 1] < A[j]) {
                     swap = A[j + 1];
                     A[j + 1] = A[j];
                     A[j] = swap;
                 }
            }
       }
}

For example:
50
26
7
9
15
27
Array A

Pass # 1:



26
50
7
9
15
27
50 and 26 swapped
26
7
50
9
15
27
50 and 7 swapped
26
7
9
50
15
27
50 and 9 swapped
26
7
9
15
50
27
50 and 15 swapped
26
7
9
15
27
50
50 and 27 swapped


Pass # 2:


26
7
9
15
27
50
Array at the beginning of pass #2
7
26
9
15
27
50
26 and 7 swapped
7
9
26
15
27
50
26 and 9 swapped
7
9
15
26
27
50
26 and 15 swapped

After pass #2 the array is sorted but the loop wil continue until the end.
If A is the array to be sorted, A.length-1 passes are made. Adjacent elements are checked in each pass from the first to A.length-i-1. The elements until the end of the array are already sorted.

Bubble sort is slower than many other sorting algorithms. Complexity is O(n2)

No comments :

Post a Comment