Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 8

SELECTION SORT

The selection sort is a combination of


searching and sorting.
In selection sort, sorting is done after
selecting a particular smallest or largest
element from an array and shifted it to a
particular location in an array.
During each pass, the unsorted element
with the smallest (or largest) value is
moved to its proper position in the array.
Let's look at our same table of elements
using a selection sort for ascending
order:
Arra 40 50 60 10 30 20
y
1- 10 50 60 40 30 20
pass
2- 10 20 60 40 30 50
pass
3- 10 20 30 40 60 50
pass
4- 10 20 30 40 60 50
pass
5- 10 20 30 40 50 60
pass
The number of times the sort passes through
the array is one less than the number of items
in the array.
In the selection sort, the inner loop finds the
next smallest (or largest) value and the outer
loop places that value into its proper location.
Lets watch a video which will give you a basic
idea of a selection sort.
Please co-operate.
Lets look at coding of it in c++:
#include<iostream>
using namespace std;
void selectionsort(int *array,int length)
{
int i,j,min,minat,temp;
for(i=0;i<(length-1);i++)
{
minat=i;
min=array[i];
for(j=0;j<length;j++)
{
if(min>array[j])
{
minat=j;
min=array[j];
}
}
temp=array[i];
array[i]=array[minat];
array[minat]=temp;
}
}

void printelements(int *array,int length)
{
int i;
for(i=0;i<length;i++)
cout<<array[i]<< <<;
}
int main()
{
int array[100],n,i;
cout<<enter number of element you wants to enter in an array;
cin>>n;
if(n<0)
{
cout<<enter proper positive element;
cin>>n;
}
for(i=0;i<n;i++)
{
cout<<enter values in array;
cin>>array[i];
}
selectionsort(array,n);
printelement(array,n);
return 0;
}

Any query?
Any question or any point which you
doesnt get?
THANK YOU!

You might also like