Selection Sort

About

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #include <bits/stdc++.h> using namespace std; void print(int a[], int n) { for (int i = 0; i < n; i++) { cout << a[i] << " "; } cout << endl; } // SelectSort void SelectSort(int a[], int n) { for (int i = 0; i < n - 2; i++) { int Imin = i; for (int j = i + 1; j < n; j++) { if (a[Imin] > a[j]) { Imin = j; } } int temp = a[i]; a[i] = a[Imin]; a[Imin] = temp; } print(a, n); } signed main(){ int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } SelectSort(a, n); print(a, n); return 0; }

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. The subarray which is already sorted. Remaining subarray which is unsorted. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.

Approach

  • Initialize minimum value(min_idx) to location 0
  • Traverse the array to find the minimum element in the array
  • While traversing if any element smaller than min_idx is found then swap both the values.
  • Then, increment min_idx to point to next element Repeat until array is sorted

Time Complexity

  • Worst Case Time Complexity is: O(N^2)
  • Average Case Time Complexity is: Ω(N^2)
  • Best Case Time Complexity is: Ω(N^2)