Insertion Sort in C++

Source Code:

//insertion sort
#include<iostream>
#include<stdlib.h>
using namespace std;
class insertion
{
    private:
        int n,key;
        int stack[100],temp;        
    public:
        void getinput()
        {
            cout<<"How many nuumbers in array? ";
            cin>>n;
            cout<<"Enter "<<n<<" numbers: ";
            for (int i=0;i<n;i++)
                cin>>stack[i];
        }
        void ascending()
        {
            for (int i=1;i<n;i++) 
            {
                while(i>0 && stack[i]<stack[i-1])
                {
                    temp=stack[i];
                    stack[i]=stack[i-1];
                    stack[i-1]=temp;
                    i--;
                }
            } 
        }
        void descending()
        {
            for (int i=1;i<n;i++) 
            {
                while(i>0&&stack[i]>stack[i-1])
                {
                    temp=stack[i];
                    stack[i]=stack[i-1];
                    stack[i-1]=temp;
                    i--;
                }
            } 
        }
        void showoutput()
        {
            cout<<"\nThe sorted numbers are: ";
            for(int j=0;j<n;j++)
                cout<<stack[j]<<"\t";
            cout<<"\n-----------------------------------------------                       --------------\n";
        }         
}; 
int main()
{
    insertion q;
    int choice;
    cout<<"\n**************************\n******INSERTION                         SORT******\n**************************\n";
    while (1)
    {
        cout<<"\n1-> Sort in ascending order\n";
        cout<<"2-> Sort in descending order\n";
        cout<<"3-> Exit\n";
        cout<<"\n\nEnter your choice(1, 2 or 3): ";
        cin>>choice;
        switch(choice)
        {
            case(1):
                q.getinput();
                q.ascending();
                q.showoutput();
                break;
            case(2):
                q.getinput();
                q.descending();
                q.showoutput();                
                break;
            case(3):
                exit(1);
        }   
    } 
    system("pause");
    return 0;
}



Output:



No comments:

Post a Comment