Skip to main content

Command Palette

Search for a command to run...

Selection Sorting

Published
2 min readView as Markdown

Algorithm and Intuition : (Bigger at Last)

Usage : The Algorithm is used for sorting the sequence.

What Algo Tells : This algorithm works on the principle that in each Iteration , we place the element at the current index into its correct position such that smaller on its left and larger on its right by rule of larger on the last.

Steps in Algorithms :

  1. Firstly we have to iterate to each element once as a current picker to place it correct position but think it of as it working principle we compare the current index value to its right all members if current value is larger then we swap it so does we need to check last element after (n-1) elements?? (Does last element itself be the larger or not) .

  2. so first iteration space is (1 to n-1) for 1-based indexing algorithm and (n) size array

  3. now for each current ith index we have to check its right all remaining elements to put it to its correct position so its iteration space is (current_index+1 to _?_ ) , Yes (n) because it compare last element also.

Code :

Given :

int n : size of the array.

int arr[n] : n elements in the array.

for(int i = 1 ; i <= (n-1) ; i++){

for(int j = i+1 ; j <= n ; j++){

if(arr[i] > arr[j]) swap(arr[i],arr[j]);

}

}

Time Complexity : O(N²)

Space Complexity : O(1)

ThankYou !!

Archit Dwivedi