Javatpoint Logo
Javatpoint Logo

Selection Sort

The selection sort enhances the bubble sort by making only a single swap for each pass through the rundown. Indorder 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) st pass.

ALGORITHM: SELECTION SORT (A)
1. k ← length [A]
2. for j ←1 to n-1
3. smallest ←  j
4. for I ← j + 1 to k
5. if A [i] < A [ smallest]
6. then smallest ←  i
7. exchange (A [j], A [smallest])

Analysis:

  1. Input: n elements are given.
  2. Output: the number of comparisons required to make sorting.
  3. Logic: If we have n elements in selection sort, then n-1 passes are required to find a sorted array.
 In pass 1: n-1 comparisons are required
 In pass 2:  n-2 comparisons are required
 In pass 3: n-3 comparisons are required
............................................................................
...............................................................................
 In pass n-1: 1 comparison is required 
 Total comparisons: T (n) = (n-1) + (n-2) + (n-3) +........+ 1
                          = DAA Selection Sort
                          = o (n2)
	Therefore complexity is of order n2 

Example:

Sort the following array using selection sort: A [] = (7, 4, 3, 6, 5).

A [] =

7 4 3 6 5

1 Iteration:

Swap 7 and 3

3 4 7 6 5

2nd iteration:

No Swap

3 4 7 6 5

3rd iteration:

Swap 7 and 5

3 4 5 6 7

4th iteration:

No Swap

3 4 5 6 7

Finally, the sorted list is:

3 4 5 6 7

Next TopicInsertion Sort




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA