selection sort algorithm in data structure

Join Our Official AiJobsAdda Telegram Channel

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:-

 

Predict the output of following C++ program in cpp

Print 1 to 100 in C++, without loop and recursion

Factorial Using Loop Example Program In C++

bfs algorithm in data structure (BFS)

if..else Statement Example Program In C++

For Loop Example Program In C++

Program to find the sum of each row & column of a matrix of size n x m andif matrix is square, find the sum of the diagonals also.

 tudo app using html and css javascript

how to create age calculator in html project

how to make toast in html css and javascript

how to make copy to clipboard in javascript

how to create email validation in javascript

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 .