Javatpoint Logo
Javatpoint Logo

Selection Sort

In selection sort, the smallest value among the unsorted elements of the array is selected in every pass and inserted to its appropriate position into the array.

First, find the smallest element of the array and place it on the first position. Then, find the second smallest element of the array and place it on the second position. The process continues until we get the sorted array.

The array with n elements is sorted by using n-1 pass of selection sort algorithm.

  • In 1st pass, smallest element of the array is to be found along with its index pos. then, swap A[0] and A[pos]. Thus A[0] is sorted, we now have n -1 elements which are to be sorted.
  • In 2nd pas, position pos of the smallest element present in the sub-array A[n-1] is found. Then, swap, A[1] and A[pos]. Thus A[0] and A[1] are sorted, we now left with n-2 unsorted elements.
  • In n-1th pass, position pos of the smaller element between A[n-1] and A[n-2] is to be found. Then, swap, A[pos] and A[n-1].

Therefore, by following the above explained process, the elements A[0], A[1], A[2],...., A[n-1] are sorted.

Example

Consider the following array with 6 elements. Sort the elements of the array by using selection sort.

A = {10, 2, 3, 90, 43, 56}.

Pass Pos A[0] A[1] A[2] A[3] A[4] A[5]
1 1 2 10 3 90 43 56
2 2 2 3 10 90 43 56
3 2 2 3 10 90 43 56
4 4 2 3 10 43 90 56
5 5 2 3 10 43 56 90

Sorted A = {2, 3, 10, 43, 56, 90}

Complexity

Complexity Best Case Average Case Worst Case
Time Ω(n) θ(n2) o(n2)
Space o(1)

Algorithm

SELECTION SORT(ARR, N)

  • Step 1: Repeat Steps 2 and 3 for K = 1 to N-1
  • Step 2: CALL SMALLEST(ARR, K, N, POS)
  • Step 3: SWAP A[K] with ARR[POS]
    [END OF LOOP]
  • Step 4: EXIT

SMALLEST (ARR, K, N, POS)

  • Step 1: [INITIALIZE] SET SMALL = ARR[K]
  • Step 2: [INITIALIZE] SET POS = K
  • Step 3: Repeat for J = K+1 to N -1
    IF SMALL > ARR[J]
    SET SMALL = ARR[J]
    SET POS = J
    [END OF IF]
    [END OF LOOP]
  • Step 4: RETURN POS

C Program

Output:

printing sorted elements...
7
9
10
12
23
23
34
44
78
101

C++ Program

Output:

printing sorted elements...
7
9
10
12
23
23
34
44
78
101

Java Program

Output:

printing sorted elements...
7
9
10
12
23
23
34
44
78
101

C# Program

Output:

printing sorted elements...
7
9
10
12
23
23
34
44
78
101

Python Program

Output:

printing sorted elements...
7
9
10
12
23
23
34
44
78
101

Rust Program

Output:

printing sorted elements...

7
9
10
12
23
23
34
44
78
101

JavaScript Program

Output:

printing sorted elements ...
7
9
10
12
23
23
34
44
78
101

PHP Program

Output:

printing sorted elements ...
7
9
10
12
23
23
34
44
78
101

Next TopicShell Sort




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA