Selection Sort in C++





Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations.

Program:

#include <iostream.h>

void selectionSort(int *array,int length)//selection sort function
{
int i,j,min,minat;
for(i=0;i<(length-1);i++)
{
minat=i;
min=array[i];

for(j=i+1;j<(length);j++) //select the min of the rest of array
{
if(min>array[j]) //ascending order for descending reverse
{
minat=j; //the position of the min element
min=array[j];
}
}
int temp=array[i] ;
array[i]=array[minat]; //swap
array[minat]=temp;

}

}

void printElements(int *array,int length) //print array elements
{
int i=0;
for(i=0;i<10;i++)
cout<<array[i]<<endl;
}

void main()
{

int a[]={9,6,5,23,2,6,2,7,1,8}; // array to sort
selectionSort(a,10); //call to selection sort
printElements(a,10); // print elements
}

if you find any bug in the above program. let us know about it. Please post your complaint at pctech@gadgetcage.com.


We'll send more interesting posts like Selection Sort in C++ to you!
Enter your Email Address:
Join us on Facebook.

Speak Your Mind

*