Implement selection sort on a list of numbers
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const
int MAX=50;
class
array
{
private:
int arr[MAX];
int count;
public:
array()
{count=0;}
void add(int);
void display(void);
void sort();
};
void
array::add(int item)
{ if(count<MAX)
{
arr[count]=item;
count++;
}
else
cout<<"\nArray is
full\n ";
}
void
array::display()
{ cout<< "\nThere
are"<<count<<"elements in the list \n";
cout<<"\n
They are : \n";
for(int
i=0;i<count;i++)
cout<<arr[i]<<" ";
}
void
array::sort()
{ int i,j;
int min,temp;
for(i=0;i<count-1;i++)
{ min=i;
for(j=i+1;j<count;j++)
if(arr[j]<arr[min])
min=j;
temp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
}
return;
}
void
main()
{ int element,n,i,c;
array selection;
while(1)
{ clrscr();
cout<<"\nPerform
the Selection Sort";
cout<<"\n-------------------------------";
cout<<"\n1.Input
data into the list";
cout<<"\n2.Display
data in the list";
cout<<"\n3.Sort
the list";
cout<<"\n4.Exit
from the program";
do
{ cout<<"\nSelect your choice(1:4)";
cin>>c;
cout<<"";
}
while((c<1)||(c>4));
if(c==4)exit(1);
clrscr();
switch(c)
{ case 1 :
clrscr();
cout<<"How many
elements : ";
cin>>n;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<
" : ";
cin>>element;
selection.add(element);
}
break;
case 2 :
clrscr();
selection.display();
break;
case 3 :
clrscr();
selection.sort();
cout<<"List is
successfully sorted \n";
break;
}
cout<<"\nPress any key to
continue............";
getch();
}
}
No comments:
Post a Comment