# What is selection sort?self.__wrap_b=(t,n,e)=>{e=e||document.querySelector(`[data-br="\${t}"]`);let a=e.parentElement,r=R=>e.style.maxWidth=R+"px";e.style.maxWidth="";let o=a.clientWidth,c=a.clientHeight,i=o/2-.25,l=o+.5,u;if(o){for(;i+1<l;)u=Math.round((i+l)/2),r(u),a.clientHeight===c?l=u:i=u;r(l*n+o*(1-n))}e.__wrap_o||(typeof ResizeObserver!="undefined"?(e.__wrap_o=new ResizeObserver(()=>{self.__wrap_b(0,+e.dataset.brr,e)})).observe(a):process.env.NODE_ENV==="development"&&console.warn("The browser you are using does not support the ResizeObserver API. Please consider add polyfill for this API to avoid potential layout shifts or upgrade your browser. Read more: https://github.com/shuding/react-wrap-balancer#browser-support-information"))};self.__wrap_b(":Rid9j6:",1)

Sorting in general means arranging the elements of an unsorted array either in ascending or descending order. There is a requirement to sort array elements to keep them organized and for quick access. This reduces time complexity, one of the significant constraints while dealing with large data.

## Introductionš

Selection sort is one such algorithm for sorting, where we find the least valued element in each iteration and swapped with the element at the beginning of every sub-array.

The array will be divided into two sub-arrays:

• Sorted sub-array
• Unsorted sub-array

We shall append (add) the smallest element from the unsorted sub-array to the end of the sorted sub-array in order to better explain the concept.

## Algorithmš¢

1. Get the array input from the user
2. Use 2 iterators: one to maintain the sorted sub-array and the other for the unsorted sub-array.
3. Compare the current element and swap it with the least possible value in the remaining sub-array.
4. Continue the same approach with the next element until the entire array/segment is sorted.

## Implementationāļø

Letās begin implementing the above using C++. To be clear the logic remains the same, only the syntax of every programming language changes.

```.wp-block-code {
border: 0;
}

.wp-block-code > div {
overflow: auto;
}

.shcb-language {
border: 0;
clip: rect(1px, 1px, 1px, 1px);
-webkit-clip-path: inset(50%);
clip-path: inset(50%);
height: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
width: 1px;
word-wrap: normal;
word-break: normal;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```#include <bits/stdc++.h>
using namespace std;

void swapElements(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

void sort_selection(int sorted[], int arrLen) {
int i, j, low;

for (int i = 0; i < arrLen - 1; i++) {
low = i;
for (int j = i + 1; j < arrLen; j++) {
if (sorted[j] < sorted[low]) { low = j; }
}

if (low != i) { swapElements(&sorted[low], &sorted[i]); }
}
}

int main() {
int inArray[] = { 40, 10, 20, 30, 50 };

int arrLen = sizeof(inArray)/ sizeof(inArray[0]);

cout << "Unsorted Array: ";

for (int i = 0; i < arrLen; i++)
cout << inArray[i] << " ";

sort_selection(inArray, arrLen);

cout << endl << "Sorted Array: ";

for (int i = 0; i < arrLen; i++)
cout << inArray[i] << " ";

return 0;
}

```Code language: C++ (cpp)```

The above code is the C++ implementation of the selection sort algorithm. Letās begin with the `main` function. Initially, we created an integer array named `arr` and stored five random values. Also, calculate the value of the size of the array and store it in the variable `n`. Then we call the `selectionSort` function defined above. We pass two parameters: the array as such and the size of the array.

The `selectionSort` function has three variables defined namely `i`, `j`, and `low`. `i` and `j` are iteration variables. `low` a variable is used to store the minimum value of the unsorted subarray.

### Theoretical Understandingš

The outer for-loop runs from 0 to one less than the size of the array. The reason we skip one iteration is that the last element will be already in the correct position. In every iteration, we store the value of low to i. Then we run an inner for-loop from `i + 1` to `n`. In every iteration, we check if the current element in the unsorted sub-array is less than the value at the position `i`. If true we update the value of `low`. After the inner for-loop completes its iterations we check if the current value of the variable `low` is the same as the value of `i` (initialized above). If true then we continue with the next iteration. If not then we swap the value of elements at their position using `swap` the function. It is based on the concept of the call-by-reference method. Finally, when the outer for-loop completes its iteration we jump back to the main program. Then we display the sorted array.

This is the working of the selection-sort algorithm. The concept behind it lies the same but only the syntax changes in other programming languages.

Visual interpretation of whatever is conveyed in words is available here:

## Space and Time Complexity

According to the selection sort algorithm we need to iterate the loop and check the condition of finding the smallest element. Each of them requires O(n) time complexity. Therefore the net time complexity is:

O(n) * O(n) = O(n^2)

šAverage Case: Ī(n^2)

š­Worst Case: O(n^2)

Here we donāt require any extra array while performing the sorting algorithm. Hence, the space complexity is O(1).

## Conclusionš

• Selection sort utilizes two sub-arrays: sorted and unsorted sub-array.
• After the end of each iteration, we bring the lowest or highest element in the sorted sub-array.
• It requires very less space complexity i.e. O(1) and time-complexity of O(n^2)
• Hereās the link to the codedamn playground which contains the code and you could play directly with the integrated terminal and editor.

Sharing is caring

Did you like what Sriniketh J wrote? Thank them for their work by sharing it on social media.

0/10000