Sunteți pe pagina 1din 3

Sorting Algorithms in Java

Time Growth Rate Best Case Bubble Sort N Time Growth Rate Average Case N2 Time Growth Rate Worst Case N2

Bubble Sort
Like the selection sort this implementation of a bubble sort takes up to N2 operations to sort a list in the worst case. A bubble sort can be a good choice if the data is likely to already be sorted because if it is the bubble sort would require only N-1 comparisons and no exchanges.

The bubble sort compares adjacent 25 9 13 items and swaps 9 25 13 them if they are 9 25 13 out of order. 9 13 25 9 13 25 The bubble sort 9 13 25 starts by 9 13 25 comparing the first and second items in a list. 9 13 25 They are swapped 9 13 25 if the first item is 9 13 25 larger then the 9 13 12 second item. Then the second 9 13 12 and third items are 9 13 12 compared and 9 12 13 swapped if necessary and so 9 13 12 on. The largest items bubble to the right. After each pass one more item will be in it's correct position at the end

47 47 47 47 47 47 12 12 12 12 25 25 25 25 25

Pass One (4 Comparisons) 12 Compare 12 Swap 12 Compare 12 Swap 12 Compare (No Swap) 12 Compare 47 Swap Pass Two (3 Comparisons) 47 Compare (No Swap) 47 Compare (No Swap) 47 Compare 47 Swap Pass Three (2 Comparisons) 47 Compare (No Swap) 47 Compare 47 Swap Pass Four (1 Comparisons) 47 Compare (No Swap)

of the array. Passes are made over the array until there has been no swaps made. The figure to the right illustrates this. The largest item found in each search is in blue. The item it is swapped with is in green . The items that have already been sorted are Bold. Below is an implementation of the Bubble Sort algorithm. L specifies were in the array to start sorting and R specifies what element to stop sorting at. Each time the outer loop executes one more item will be in it's correct position at the end of the array. The bubble sort will terminate as soon as there has been no exchanges made in the inner loop.
public static void bubbleSort(double arrayToSort[], int L, int R) { int I=0; boolean sorted = false; double temp; for ( ; (R > L) && !sorted; R--) { sorted = true; // assume that array is sorted + 1] ) for (I = L; I < R; I++) if ( arrayToSort[I] > arrayToSort[I { arrayToSort[I + 1]; temp = arrayToSort[I]; arrayToSort[I] =

arrayToSort[I + 1] = temp; sorted = false; // there was a swap so array may not be sorted.

} }

Next week I will present an implementation of a Insertion Sort.


public static void bubbleSort(double arrayToSort[], int L, int R) { int I=0; boolean sorted = false; double temp; for ( ; (R > L) && !sorted; R--) { sorted = true; // assume that array is

sorted

for (I = L; I < R; I++) if ( arrayToSort[I] > arrayToSort[I + 1] ) { temp = arrayToSort[I]; arrayToSort[I] = arrayToSort[I + 1]; arrayToSort[I + 1] = temp; sorted = false; // there was a swap so array may not be sorted. } } }

S-ar putea să vă placă și