1 / 11

CSC 172 DATA STRUCTURES

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

Download Presentation

CSC 172 DATA STRUCTURES

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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. BUBBLE SORT 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. 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; }

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

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

More Related