Slide 6
Slide 6
Slide 6
Selection Sort
► The selection sort enhances the bubble sort by making only a single swap for
each pass through the rundown. In order to do this, a selection sort searches
for the biggest value as it makes a pass and, after finishing the pass, places it
in the best possible area. Similarly, as with a bubble sort, after the first pass,
the biggest item is in the right place. After the second pass, the following
biggest is set up. This procedure proceeds and requires n-1 goes to sort n item
since the last item must be set up after the (n-1) th pass.
ALGORITHM: SELECTION SORT (A)
1. 1. k ← length [A]
2. 2. for j ←1 to n-1
3. 3. smallest ← j
4. 4. for I ← j + 1 to k
5. 5. if A [i] < A [ smallest]
6. 6. then smallest ← i
7. 7. exchange (A [j], A [smallest])
How Selection Sort works
► In the selection sort, first of all, we set the initial element as a minimum.
► Now we will compare the minimum with the second element. If the second
element turns out to be smaller than the minimum, we will swap them,
followed by assigning to a minimum to the third element.
► Else if the second element is greater than the minimum, which is our first
element, then we will do nothing and move on to the third element and then
compare it with the minimum.
► We will repeat this process until we reach the last element.
► After the completion of each iteration, we will notice that our minimum has
reached the start of the unsorted list.
Continued…
► For each iteration, we will start the indexing from the first element of the
unsorted list. We will repeat the Steps from 1 to 4 until the list gets sorted or
all the elements get correctly positioned.
► Consider the following example of an unsorted array that we will sort with
the help of the Selection Sort algorithm.
1st Iteration:
► Set minimum = 7
• Compare a0 and a1
Continued…
► Set minimum = 4
• Compare a1 and a2
Continued…
► Set minimum = 7
• Compare a2 and a3
Continued…
► Set minimum = 6
• Compare a3 and a4
Continued…
► In the selection sort algorithm, the time complexity is O(n2) in all three
cases. This is because, in each step, we are required to
find minimum elements so that it can be placed in the correct
position. Once we trace the complete array, we will get our minimum
element.
?