Selection Sort
Selection Sort
Selection Sort
array sorting welldev interview
C++
/*
author: remonhasan
Topic: Selection Sort
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
int a[N];
selectionSort(a, N);
for (int i = 0; i < N; i++) cout << a[i] << " ";
return 0;
}
Concepts of Selection Sort:
Selection Sort is a simple and intuitive comparison-based sorting algorithm. The concept behind it
is to repeatedly select the minimum (or maximum) element from an unsorted portion of the array
and swap it with the element at the beginning (or end) of the unsorted part.
Here’s the basic idea:
1. Start with the first element:
• Assume that the first element is the minimum in the array.
2. Search for the smallest (or largest) element in the remaining unsorted portion of the array.
3. Swap the smallest element found with the first element.
4. Move to the next element: Now, consider the first element sorted, and repeat the process for
the remaining unsorted portion of the array.
5. Repeat the above steps for each element until the entire array is sorted.
• Third pass: In the subarray [4, 3, 5] , the smallest element is 3 , which is swapped with 4 .
Now, the array looks like: [1, 1, 3, 4, 5] .
• Fourth pass: In the subarray [4, 5] , the smallest element is 4 , which is already in place. The
array remains: [1, 1, 3, 4, 5] .
After these steps, the array is sorted: [1, 1, 3, 4, 5] .
Explanation
Let's break down this portion of code step by step, explaining each part with reference to your
array 3, 1, 4, 1, 5 :
Code Breakdown:
C++
Let's explain each part of this code, step by step, using your array 3,
1, 4, 1, 5 .
First Pass ( i = 0 ):
• minIndex = 0 , assuming arr[0] = 3 is the smallest.
• Compare arr[1] = 1 with arr[0] = 3 : Update minIndex = 1 .
• Compare arr[2] = 4 with arr[1] = 1 : No change.
• Compare arr[3] = 1 with arr[1] = 1 : No change.
• Compare arr[4] = 5 with arr[1] = 1 : No change.
• After inner loop: minIndex = 1 .
• Swap arr[0] and arr[1] : The array becomes [1, 3, 4, 1, 5] .
Second Pass ( i = 1 ):
• minIndex = 1 , assuming arr[1] = 3 is the smallest.
• Compare arr[2] = 4 with arr[1] = 3 : No change.
• Compare arr[3] = 1 with arr[1] = 3 : Update minIndex = 3 .
• Compare arr[4] = 5 with arr[3] = 1 : No change.
• After inner loop: minIndex = 3 .
• Swap arr[1] and arr[3] : The array becomes [1, 1, 4, 3, 5] .
Third Pass ( i = 2 ):
• minIndex = 2 , assuming arr[2] = 4 is the smallest.
• Compare arr[3] = 3 with arr[2] = 4 : Update minIndex = 3 .
• Compare arr[4] = 5 with arr[3] = 3 : No change.
• After inner loop: minIndex = 3 .
• Swap arr[2] and arr[3] : The array becomes [1, 1, 3, 4, 5] .
Fourth Pass ( i = 3 ):
• minIndex = 3 , assuming arr[3] = 4 is the smallest.
• Compare arr[4] = 5 with arr[3] = 4 : No change.
• After inner loop: minIndex = 3 .
• No swap needed as minIndex = i .
Fifth Pass ( i = 4 ):
• The last element is already in place, so no comparisons or swaps are needed.