COMP 14: Sorting June 14, 2000 Nick Vallidis
Announcements zP4 is due today!
Homework zRead 6.3 zP5 is due next Tuesday (June 20, 2000)
Review zHow do we declare and instantiate an array? zHow can we tell how many values there are in an array? zWhat's the Java control statement that's super useful with arrays? zSo how are Strings and arrays related?
Sorting zPut elements of an array in some order yalphabetize names yorder grades lowest to highest zTwo simple sorting algorithms yselection sort yinsertion sort
Selection Sort zSorts by putting values directly into their final, sorted position zFor each value in the list, the selection sort finds the value that belongs in that position and puts it there
Selection Sort General Algorithm zScan the list to find the smallest value zExchange that value with the value in the first position in the list zScan rest of list for the next smallest value zExchange that value with the value in the second position in the list zAnd so on, until you get to the end of the list
Selection Sort At Work… items 4 swaps
code for selection sort (done in class) int tmp; int[] myArray = new int[10000]; for (int j=0; j<myArray.length; j++) { int indexMin=j; for (int i=j; i<myArray.length; i++) { if (myArray[i] < myArray[indexMin]) indexMin = i; } tmp = myArray[j]; myArray[j] = myArray[indexMin]; myArray[indexMin] = tmp; }
Selection Sort zOuter loop controls the index in the array where the next chosen element goes zInner loop searches for the minimum of the rest of the array zEach iteration of the outer loop adds one more value to the sorted subset of the list, until the entire list is sorted
Selection Sort zSorts in ascending order zCan be changed to sort in descending order ylook for max instead of min
Insertion Sort zLike we’d actually sort things zInsert each new item into an already sorted list zEach unsorted element is inserted at the appropriate spot in the sorted subset until the list is ordered
Insertion Sort General Algorithm zSort the first two values (swap, if necessary) zInsert list’s third value into the appropriate position relative to the first two (which are already sorted) zInsert fourth into the appropriate position relative to the three sorted zEach time insertion made, number of values in the sorted subset increases by one zRepeat until all values in list are sorted zOther values in array shift to make room for inserted elements
Insertion Sort At Work…
Insertion Sort zOuter loop controls the index in the array of the next value to be inserted zInner loop compares the current insert value with values stored at lower indexes zEach iteration of the outer loop adds one more value to the sorted subset of the list, until the entire list is sorted