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

Friday, July 22, 2011

Progrma for quick sort

/*Serial No.160     [swami141.cpp]*/

#include<stdio.h>
#include<conio.h>
#define MAX 10
    
int arr[MAX],num,n;
    
void quicksort(int,int);
void main()
{
int i,first,last;
clrscr();
printf("Enter the number of elements in the list: ");
scanf("%d",&n);
printf("Enter the elements: \n");
for(i=0;i<n;i++)
        {
        scanf("%d",&arr[i]);
        }
quicksort(0,n-1);// pass the first and last index
printf("The sorted elements: \n");
for(i=0;i<n;i++)
        {
         printf("%d..\n",arr[i]);
        }
getch();
}
    
void quicksort(int first,int last)
       {
        int temp,low,high,midval;
        low=first;//array index
        high=last;//array index
        midval=arr[(first+last)/2]; // mid element
    
        do
        {
            while(arr[low]<midval)
            {
                low++;
            }
            while(arr[high]>midval)
            {
                high--;
            }
            if(low<=high)
            {
                temp=arr[low];
                arr[low]=arr[high];
                arr[high]=temp;
                low++;
                high--;
            }
        }while(low<=high);
        if(first<high)
        {
            quicksort(first,high);
        }
        if(low<last)
        {
            quicksort(low,last);
        }
    }

Program to implement Heap Sort

/*Serial No.151     [swami133.cpp]*/

#include<stdio.h>
#include<conio.h>

void restoreHup(int*,int);
void restoreHdown(int*,int,int);

void main()
{
    int a[20],n,i,j,k;
    clrscr();
    printf("Enter the number of elements to sort : ");
    scanf("%d",&n);

    printf("Enter the elements :");
    for(i=1;i<=n;i++){
        scanf("%d",&a[i]);
        restoreHup(a,i);
    }
    j=n;
    for(i=1;i<=j;i++)
    {
        int temp;
        temp=a[1];
        a[1]=a[n];
        a[n]=temp;
        n--;
        restoreHdown(a,1,n);
    }

    n=j;
    printf("Here is it...");
    for(i=1;i<=n;i++)
        printf("%4d",a[i]);
    getch();
}

void restoreHup(int *a,int i)
{
    int v=a[i];
    while((i>1)&&(a[i/2]<v))
    {
        a[i]=a[i/2];
        i=i/2;
    }
    a[i]=v;
}

void restoreHdown(int *a,int i,int n)
{
    int v=a[i];
    int j=i*2;
    while(j<=n)
    {
        if((j<n)&&(a[j]<a[j+1]))
            j++;
        if(a[j]<a[j/2]) break;
        a[j/2]=a[j];
        j=j*2;
    }
    a[j/2]=v;
}