Showing posts with label Sorting. Show all posts
Showing posts with label Sorting. Show all posts

Monday, 3 November 2014

Selection sort Algorithm C++ code

#include<iostream>
#include<stdlib.h>
using namespace std;
#include<conio.h>

int main()
{                char c='y';
                 while(c=='y' || c=='Y')
                 {
                 int a[20],j,count,n,temp;
                 cout<<"\nEnter number of elements to enter:";
                 cin>>n;
                 cout<<"\nEnter the elements:";
                 for(int i=0;i<n;i++)
                 {
                 cout<<endl;
                 cin>>a[i];
                 }
                 for(int i=0;i<n-1;i++)
                 {cout<<endl<<"****"<<endl;
                         count=0;
                         for(j=1;j<n-i;j++)
                         if(a[j]>a[count])
                         count=j;

                        swap(a[count],a[j-1]);//default swap function working in code blocks IDE or just change the code for explicit swapping
                          cout<<"\nAfter pass "<<i+1<<": ";
                          for(int i=0;i<n;i++)
                          cout<<a[i]<<"  ";
                 }
                cout<<"\n\n******\n\nFinal Sorted array is:";
                 for(int i=0;i<n;i++)
                 cout<<"  "<<a[i];
                 cout<<"\n\nWant to continue?(Y/N): ";
                 cin>>c;
                 system("cls");
                 }

}

Quick Sort Algorithm C++ code

#include<iostream>
using namespace std;
//#include<conio.h>
int quicksort (int[],int,int);
int pos;
int main()
{
    int ar[7],pivot,last;
    cout<<"\n Enter the 7 elts in array:"<<endl;
    for(int i=0;i<7;i++)
        cin>>ar[i];
        quicksort(ar,0,7);
        cout<<"\n*************************Sorted array*****************************\n\n";
        for(int i=0;i<7;i++)
        cout<<"\t"<<ar[i];
//        getch();
}

 int quicksort(int ar[],int pivot,int last)
{
    int pos=pivot;

    if(ar[pivot]==ar[last])
    return 0;

    else
    {
    for(int i=pivot+1;i<last;i++)
        if(ar[i]<ar[pivot])
        {
            int temp;
            temp=ar[i];
            int j=i;
            while(j--!=pos)
            {
                ar[j+1]=ar[j];
            }
             ar[j+1]=temp;
             pos++;
        }
        quicksort(ar,pivot,pos);
        quicksort(ar,pos+1,7);
    }
}