Download presentation
Presentation is loading. Please wait.
Published byJack Brooks Modified over 9 years ago
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.