110 likes | 238 Views
CSC 172 DATA STRUCTURES. SORTING. Exercise : write a method that sorts an array. void mysort(int [] a) { }. BUBBLE SORT. BUBBLE SORT. Works by comparing adjacent pairs Values “bubble up” to correct position O(n^2). BUBBLE SORT. void bubblesort(AnyType [] a) {
E N D
SORTING Exercise : write a method that sorts an array. void mysort(int [] a) { }
BUBBLE SORT Works by comparing adjacent pairs Values “bubble up” to correct position O(n^2)
BUBBLE SORT void bubblesort(AnyType [] a) { for (int i = 0 ; i < a.length ; i++){ for (int j = 0 ; j < a.length - 1 ; j++){ if (a[j].compareTo(a[j+1]) > 0) swap(a,j,j+1); } } }
INSERTION SORT void insertionsort(AnyType [] a) { int j ; for (int p = 1 ; p < a.length ; p++){ AnyType tmp = a[p]; for (j = p ; j>0 && tmp.compareTo(a[j-1]) < 0; j--){ a[j] = a[j-1]; } a[j] = tmp; }
INSERTION SORT Works by comparing adjacent pairs Values “bubble up” to correct position Takes advantage of sorted sections of the array Still O(n^2) but O(n(n+1)/2)
SHELL SORT void shellsort(AnyType [] a) { int j ; for (int gap = a.length / 2 ; gap > 0 ; gap /= 2){ for (int i = gap ; i < a.length ; i++){ AnyType tmp = a[i]; count++; for (j = i ; j >= gap && tmp.compareTo(a[j-gap]) < 0; j -= gap) { a[j] = a[j-1]; } a[j] = tmp; } }
SHELL SORT Works by comparing distant pairs Sub-quadratic but still polynomial O(n^(3/2)) with Hibbard's increments