what is sorting ??
Arranging anything in an ascending or descending manner is called sorting.
In computer science when we want to sort something we use different kinds of sorting Algorithms(Step-by-step instructions to do a particular job) Selection sort is one of them.
Selection sorting is a simple sorting technique that divides the input into two parts.
what have to keep in your mind is
Find the smallest element in the given input and swap it with the first element.
consider that the first element in the input will be our minimum element
repeat this thing until the entire input(maybe an array)
is not sorted.
Selection sort always takes the same number of key comparisons โ N(N โ 1)/2.
Implementation in C++
#include<bits/stdc++.h>
using namespace std;
// function to print the Array
void printArray(int array[],int size){
for(int i = 0; i<size; i++){
cout<<array[i]<<" ";
} cout<<endl;
}
void selectionSort(int array[],int size){
for(int i = 0; i< size-1; i++){
int minimum = i;
for(int j = i+1; j<size; j++){
if(array[j]<array[minimum])
minimum = j;
}
swap(array[minimum],array[i]);
}
}
int main(){
int inputData[] = {20,12,10,15,2,1};
int sizeOfArray = sizeof(inputData)/sizeof(inputData[0]);
selectionSort(inputData,sizeOfArray);
cout<<"Sorted Array in Acesding order"<<endl;
printArray(inputData,sizeOfArray);
return 0;
}
i< size-1;
Because we are assuming that the first element is sorted
int j = i+1
Now compare the first element to the next element of the input Array.
For Better understanding take a pen, and copy and dry run the code.
Properties
Space Complexity: O(n)
Time Complexity: O(n2)
Sorting in Place: Yes
Stable: No
Thank you for reading my content. Be sure to follow and comment on what you want me to write about next
๐ค