Algorithm:
Step 1: Select 1St element of the list.
Step 2: Compare selected elements with other elements in the list one by one.
Step 3: For every comparison, if any element is smaller then selected element then these two are swapped.
Step 4: Repeat the same procedure with next position in the list till the end of the list.
Code:
#include<iostream> using namespace std; void selectionSort(int list[],int arraySize) { for(int i=0;i<arraySize;i++)//repeat from position 0 to n-1 { //Find the minimum in the list[i....arraySize-1] int currentMin=list[i];//list[0] consider int currentMinIndex=i;//0,1 for(int j=i+1;j<arraySize;j++) { if(currentMin>list[j]) { currentMin=list[j]; currentMinIndex=j; } } //swap list[i] with list[currentMinIndex] if(currentMinIndex!=i) { list[currentMinIndex]=list[i]; list[i]=currentMin; } } } void printArray(int arr[], int size) { int i; for(i=0;i<size;i++) { cout<<arr[i]<< " "; } cout<<endl; } int main() { int arr[5]={42,33,23,74,44}; cout<<"before selection sort: "<<endl; printArray(arr,5); cout<<"after selection sort: "<<endl; selectionSort(arr,5); printArray(arr,5); return 0; }
OUTPUT:-
Related post:-
So I hope that you learn about the selection sort algorithm in data structure And if you have any more queries about progrmming ,web Devlopment ,tech,computer relegated then feel free to discuss your problem in the comment section.Thank you so much and come back for more updates about Techgsr.co .