Ticker

6/recent/ticker-posts

Program of Quick sort in C

 

Quick sort  C code

Quick sort based on divide and conquer technique. That algorithm picks an element as a pivot and partitions the array. An array is divided into subarrays by selecting a pivot element and applying the procedure to each partitions recursively.

Quick sort C code

#include<stdio.h>
void quicksort(int a[],int first,int last);
void main()
{
    int i ,n,a[20];
    printf("enter number of element");
    scanf("%d",&n);
    printf("enter element\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    quicksort(a,0,n-1);
    printf("sorted array");
    for(i=0;i<n;i++)
    {
        printf("%d\n",a[i]);
    }
}

void quicksort(int a[],int first,int last)
{
    int i,j,pivot,temp;
    if(first<last)
    {
        pivot=first;
        i=first;
        j=last;
        while(i<j)
        {
            while(a[i]<=a[pivot]&&i<last)
            i++;
            while(a[j]>a[pivot])
            j--;
            if(i<j)
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
        temp=a[pivot];
        a[pivot]=a[j];
        a[j]=temp;
       quicksort(a,first,j-1);
       quicksort(a,j+1,last);
    }

}
Output

enter number of element5 enter element 12 2 34 5 7 sorted array2 5 7 12 34

Post a Comment

0 Comments