CS 228 meeting -*- Outline -*- ** N^2 sorting algorithms (HR 12.7) Q: How do you sort a hand of playing cards? one way: pick the largest card, place it on right, then next... *** straight selection sort draw pictures of execution (Fig 12.?) ------------------------------------------ STRAIGHT SELECTION SORT #include "slctsort.h" #include "swap.h" // Algorithm: straight selection sort void Sort( int vec[], int vSize ) { int maxIndx; // Index of largest int bot; // "False bot" for pass int i; // INV: // // for (bot = vSize-1; bot >= 1; bot--) { maxIndx = 0; // INV: // for (i = 1; i <= bot; i++) { if (vec[i] > vec[maxIndx]) { maxIndx = i; } } // ASSERT: // swap(vec[bot], vec[maxIndx]); } } ------------------------------------------ fill in the assertions (can describe it as adding a variable, bot, to the postcond) // POST: vSize >= 0 // && each vec[0..vSize] is <= vec[vSize+1] // && vec[bot+1..vSize-1] nondecreasing // && bot == vSize *** added (then delete the conjunct bot == vSize, and use negation for loop test) // INV: bot >= 0 // && each vec[0..bot] is <= vec[bot+1] // && vec[bot+1..vSize-1] nondecreasing // INV: i <= bot+1 // && vec[maxIndx] >= all vec[0..i-1] // ASSERT: vec[maxIndx] // is the maximum of vec[0..bot] simulate it (or show the video) Q: What's the worst case time complexity? *** bubble sort (HR p. 576-7) draw pictures of execution note that the "bottom" is the last element (vSize-1) or show video Can improve this for almost sorted data, because all the elements beyond the last one swapped are in order. Again, taking advantage of knowledge gained. ------------------------------------------ IMPROVED BUBBLE SORT // bubsort2.C #include "bubsort2.h" #include "swap.h" // Algorithm: an improved bubble sort void Sort( int vec[], int vSize ) { int bot; // False bot int lastSwapIndx; // last swapped int i; bot = vSize - 1; // INV: 0 <= bot < vSize // && vec[0..size-1] contains the // same values as vec[0..size-1] // && vec[bot..size-1] is sorted while (bot > 0) { lastSwapIndx = 0; // INV: 0 <= lastSwapIndx <= i <= bot // && no pair in vec[lastSwapIndx..i] // is out of order for (i = 0; i < bot; i++) if (vec[i] > vec[i+1]) { swap(vec[i], vec[i+1]); lastSwapIndx = i; } // ASSERT: i == bot && // vec[lastSwapIndx..size-1] // is sorted bot = lastSwapIndx; } } ------------------------------------------ Q: What's the worst case time complexity of this? Q: What's the best case time? When does that occur? So this isn't practical for large amounts of data (unless nearly sorted)