Program to sort out an array using Selection Sort
Thursday, March 05, 2020//program to sort out an array using selection sort
#include<iostream.h>
#include<conio.h>
void selection_sort(int A[20],int N)
{ int i,j,p,temp,small,pos;
for(i=0;i<N;i++)
{ small=A[i];
pos=i;
for(j=i+1;j<N;j++)
{ if(small>A[j])
{ small=A[j];
pos=j;
}
}
temp=A[i];
A[i]=A[pos];
A[pos]=temp;
cout<<"\n Array after iteration "<<(i+1)<<" is: ";
for(p=0;p<N;p++)
cout<<A[p]<<"\t";
}
}
void main()
{ clrscr();
int a[20],n,i;
cout<<"\n Enter the number of elements:";
cin>>n;
cout<<"\n Enter the elements of array";
for(i=0;i<n;i++)
{ cout<<"\n Enter a["<<i<<"]:";
cin>>a[i];
}
cout<<"\n Array is:";
for(i=0;i<n;i++)
cout<<a[i]<<"\t";
selection_sort(a,n);
cout<<"\n Sorted array is:";
for(i=0;i<n;i++)
cout<<a[i]<<"\t";
getch();
}
#include<iostream.h>
#include<conio.h>
void selection_sort(int A[20],int N)
{ int i,j,p,temp,small,pos;
for(i=0;i<N;i++)
{ small=A[i];
pos=i;
for(j=i+1;j<N;j++)
{ if(small>A[j])
{ small=A[j];
pos=j;
}
}
temp=A[i];
A[i]=A[pos];
A[pos]=temp;
cout<<"\n Array after iteration "<<(i+1)<<" is: ";
for(p=0;p<N;p++)
cout<<A[p]<<"\t";
}
}
void main()
{ clrscr();
int a[20],n,i;
cout<<"\n Enter the number of elements:";
cin>>n;
cout<<"\n Enter the elements of array";
for(i=0;i<n;i++)
{ cout<<"\n Enter a["<<i<<"]:";
cin>>a[i];
}
cout<<"\n Array is:";
for(i=0;i<n;i++)
cout<<a[i]<<"\t";
selection_sort(a,n);
cout<<"\n Sorted array is:";
for(i=0;i<n;i++)
cout<<a[i]<<"\t";
getch();
}
0 Comments