1 / 11

Agenda

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.

ranae
Download Presentation

Agenda

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

  2. Original data: int[] items for (int i=0; i<items.length; i++) { for (int k=i; k<items.length; k++) { …. } }

  3. index 0 1 2 3 4 Variable Trace 1st loop

  4. When to do the swap? if (items[k] < items[i]) { int temp = items[i]; items[i] = items[k]; items[k] = temp; }

  5. 1st loop

  6. Variable Trace 2nd loop index0 1 2 3 4

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

  8. 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

  9. How to change the method to make the sorting in desceding order?

  10. 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

  11. Bonus exercise Based on the array on the left, use the algorithm on last slide, trace the variable in the table

More Related