110 likes | 281 Views
Agenda. Selection sort the algorithm in the BPJ book is different than the one I wrote on the slide last time Variable trace for the selection sort Change selection sort method to sort the arry in descending order Presentations. Original data: int[] items.
E N D
Agenda • Selection sort the algorithm in the BPJ book is different than the one I wrote on the slide last time • Variable trace for the selection sort • Change selection sort method to sort the arry in descending order • Presentations
Original data: int[] items for (int i=0; i<items.length; i++) { for (int k=i; k<items.length; k++) { …. } }
index 0 1 2 3 4 Variable Trace 1st loop
When to do the swap? if (items[k] < items[i]) { int temp = items[i]; items[i] = items[k]; items[k] = temp; }
Variable Trace 2nd loop index0 1 2 3 4
Practice I • Do the same variable trace for the loop 3, 4 and 5 • You can do it on a piece of paper, but need to have 3 things for each loop: array before change variable trace table Array after change
Practice II • Do the Exercise 7 on BPJ textbook 41-5; show the result of each pass(ascending) Original data 1st pass 2nd pass 3rd pass 4th pass
How to change the method to make the sorting in desceding order?
int min, minIndex; for (int i = 0; i < a.length; i++) { min= a[i]; minIndex = i; for (int j = i; j < a.length; j++) { if (a[j] < min) { min = a[j]; minIndex = j; } } a[minIndex] = a[i]; a[i] = min; } Selection sort on BPJ book
Bonus exercise Based on the array on the left, use the algorithm on last slide, trace the variable in the table