Download presentation
Presentation is loading. Please wait.
1
Selection Sort – an array sorting algorithm
Basic operation (ascending) Divide the array into sorted and unsorted sections Keep track of the beginning of the sorted section (i.e. it’s index value) Initially the entire array will be unsorted Find the maximum element in the unsorted section Swap it into the last position (in the unsorted section) Update the sorted/unsorted partitioning Go back to step 2 Repeat until entire array is sorted (i.e. in the sorted section) Descending sort is similar Just look for minimum elements
2
spot is last element in the unsorted portion of the list
Initial Array (step 1) int list[] = { 84, 91, 76, 69, 94, 86 }; [0] [1] [2] [3] [4] [5] 84 91 76 69 94 86 list items= 6 Unsorted portion of list spot = 5 spot is last element in the unsorted portion of the list
3
Step 2 Find max element in unsorted portion list items= 6 [0] [1] [2]
[3] [4] [5] 84 91 76 69 94 86 list items= 6 Unsorted portion of list spot = 5 indMax= 4
4
Step 3 Swap max element with last element in unsorted portion list
Swap elements 86 94 list [0] [1] [2] [3] [4] [5] 84 91 76 69 94 86 items= 6 Unsorted portion of list spot = 5 indMax= 4 i.e. swap item at “spot” with item at “indMax”
5
Step 4 Update sorted/unsorted portions (i.e. update spot) list
Go back to step 2 [0] [1] [2] [3] [4] [5] 84 91 76 69 86 94 list items= 6 Unsorted Sorted spot = 4
6
Step 2 – second time Find max element in unsorted portion list
[0] [1] [2] [3] [4] [5] 84 91 76 69 86 94 list items= 6 Unsorted Sorted spot = 4 indMax= 1
7
Step 3 – second time Swap max element with last element in unsorted portion Swap elements 86 91 list [0] [1] [2] [3] [4] [5] 84 91 76 69 86 94 items= 6 Unsorted Sorted spot = 4 indMax= 1 i.e. swap item at “spot” with item at “indMax”
8
Step 4 – second time Update sorted/unsorted portions (i.e. update spot) Go back to step 2 list [0] [1] [2] [3] [4] [5] 84 86 76 69 91 94 items= 6 Unsorted Sorted spot = 3
9
Done Array is sorted (stop when spot == 0) list items= 6 [0] [1] [2]
[3] [4] [5] 69 76 84 86 91 94 items= 6 Unsorted Sorted spot = 0
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.