internal sorting a brief review and some new ideas cs 400/600 – data structures

Download Internal Sorting A brief review and some new ideas CS 400/600 – Data Structures

Post on 18-Dec-2015

213 views

Category:

Documents

0 download

Embed Size (px)

TRANSCRIPT

  • Slide 1
  • Internal Sorting A brief review and some new ideas CS 400/600 Data Structures
  • Slide 2
  • Internal Sorting2 Definitions Model: In-place sort of an array Stable vs. unstable algorithms Time measures: Number of comparisons Number of swaps Three classical sorting algorithms Insertion sort Bubble sort Selection sort
  • Slide 3
  • Internal Sorting3 Insertion Sort template void inssort(Elem A[], int n) { for (int i=1; i0) && (Comp::lt(A[j], A[j-1])); j--) swap(A, j, j-1); } i=1234567
  • Slide 4
  • Internal Sorting4 Bubble Sort template void bubsort(Elem A[], int n) { for (int i=0; ii; j--) if (Comp::lt(A[j], A[j-1])) swap(A, j, j-1); } i=1234567
  • Slide 5
  • Internal Sorting5 Selection Sort template void selsort(Elem A[], int n) { for (int i=0; ii; j--) // Find least if (Comp::lt(A[j], A[lowindex])) lowindex = j; // Put it in place swap(A, i, lowindex); } i=1234567
  • Slide 6
  • Internal Sorting6 Summary InsertionBubbleSelection Comparisons: Best Case (n) (n 2 ) (n 2 ) Average Case (n 2 ) (n 2 ) (n 2 ) Worst Case (n 2 ) (n 2 ) (n 2 ) Swaps: Best Case0 0 (n) Average Case (n 2 ) (n 2 ) (n) Worst Case (n 2 ) (n 2 ) (n) All of these algorithms are known as exchange sorts.
  • Slide 7
  • Internal Sorting7 Shellsort
  • Slide 8
  • 8 Shellsort Implementation // Modified version of Insertion Sort template void inssort2(Elem A[], int n, int incr) { for (int i=incr; i=incr) && (Comp::lt(A[j], A[j-incr])); j-=incr) swap(A, j, j-incr); } template void shellsort(Elem A[], int n) { for (int i=n/2; i>2; i/=2) // For each incr for (int j=0; j

Recommended

View more >