My Blog List

Monday, November 11, 2019

Selection Sort

In this tutorial learn how sort the data using Selection Sort Technique.

This sorting technique is combination of searching and sorting.Its working per iteration in unsorted element with smallest or largest element.The number of iteration for this sort is n-1.


Example:
arr[]=42 63 47 87 11

/*after first iteration
arr[]=11 63 47 87 42

/*after Second iteration
arr[]=11 42 47 87 63

/*after Third iteration
arrr[]=11 42 47 87 63 
/*in this iteration array element remains unchanged because no smallest element found unsorted at postion 3rd.

/*after fourth iteraation
arr[]=11 42 47 63 87


Following code shows the Selection Sort:-

#include<iostream.h>
#include<conio.h>
void selsort(int numbers[],int n)
{
int i,j,min,temp;
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(numbers[j]<numbers[min])
{
min=j;
}
}
temp=numbers[i];
numbers[i]=numbers[min];
numbers[min]=temp;
}
}
void main()
{
int *numbers,n;
clrscr();
cout<<"\nEnter the size of array:";
cin>>n;
numbers=new int[n];
cout<<"\nEnter the array element:";
for(int i=0;i<n;i++)
{
cin>>numbers[i];
}
selsort(numbers,n);
cout<<"\nSorted element:";
for(i=0;i<n;i++)
{
cout<<" "<<numbers[i];
}
getch();
}


Above code shows following output:


No comments:

Post a Comment

Multiple Inheritance in C++.

     In this tutorial Multiple Inheritance in c++. On the basis of Inheritance concept the another type of inheritance is the Multiple I...