Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 172 DATA STRUCTURES. SORTING Exercise : write a method that sorts an array. void mysort(int [] a) { }

Similar presentations


Presentation on theme: "CSC 172 DATA STRUCTURES. SORTING Exercise : write a method that sorts an array. void mysort(int [] a) { }"— Presentation transcript:

1 CSC 172 DATA STRUCTURES

2 SORTING Exercise : write a method that sorts an array. void mysort(int [] a) { }

3 BUBBLE SORT

4  Works by comparing adjacent pairs  Values “bubble up” to correct position  O(n^2)

5 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); }

6 INSERTION SORT

7 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; }

8 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)

9 SHELL SORT

10 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; }

11 SHELL SORT  Works by comparing distant pairs  Sub-quadratic but still polynomial O(n^(3/2)) with Hibbard's increments


Download ppt "CSC 172 DATA STRUCTURES. SORTING Exercise : write a method that sorts an array. void mysort(int [] a) { }"

Similar presentations


Ads by Google