C++ program to sort list of numbers using insertion sort algorithm.
C++ program to implement insertion sort
#include<iostream>
using namespace std;
class sort_list
{
int data[20];
int n;
public:
void get_data();
void insertion_sort();
void display();
};
void sort_list::get_data()
{
cout<<"How many elements two be entered ";
cin>>n;
cout<<"Enter the elements ";
for(int i=0;i<n;i++)
cin>>data[i];
}
void sort_list::insertion_sort()
{
int temp,j;
for(int i=1;i<n;i++)
{
j=i-1;
temp=data[i];
while(j>=0&&data[j]>temp)
{
data[j+1]=data[j];
j--;
}
data[j+1]=temp;
}
}
void sort_list::display()
{
cout<<"Sorted list : ";
for(int i=0;i<n;i++)
cout<<data[i]<<" ";
}
int main()
{
sort_list sort;
sort.get_data();
sort.insertion_sort();
sort.display();
return 0;
}
using namespace std;
class sort_list
{
int data[20];
int n;
public:
void get_data();
void insertion_sort();
void display();
};
void sort_list::get_data()
{
cout<<"How many elements two be entered ";
cin>>n;
cout<<"Enter the elements ";
for(int i=0;i<n;i++)
cin>>data[i];
}
void sort_list::insertion_sort()
{
int temp,j;
for(int i=1;i<n;i++)
{
j=i-1;
temp=data[i];
while(j>=0&&data[j]>temp)
{
data[j+1]=data[j];
j--;
}
data[j+1]=temp;
}
}
void sort_list::display()
{
cout<<"Sorted list : ";
for(int i=0;i<n;i++)
cout<<data[i]<<" ";
}
int main()
{
sort_list sort;
sort.get_data();
sort.insertion_sort();
sort.display();
return 0;
}
No comments:
Post a Comment