Solved programming problem

How to Sort an Array Using Quick Sort Method in C.

Source code

#include <stdio.h>

int partition(int array[],int first,int last)

{

    int i,j,temp;

    int pivot = array[last]; ///saving the last index value of array as pivot value

    for(i=first-1,j=first;j<last;j++)

    {

        if(array[j]<pivot) ///swap internal value

        {   i++;

            temp = array[j];

            array[j] = array[i];

            array[i] = temp;

        }

    }

    temp = array[last]; ///swap pivot value

    array[last] = array[i+1];

    array[i+1] = temp;

    return i+1; ///return pivot index

}

int quicksort(int array[],int first,int last)

{

    if(first>=last)

    {

        return;

    }

    int p = partition(array,first,last);  ///call the function for finding partition point

    quicksort(array,first,p-1);

    quicksort(array,p+1,last);

}

int main()

{

    int i,n,array[100];

    printf("Please Enter Array Size: ");

    scanf("%d",&n);

    printf("Please Enter Array Element: ");

    for(i=0; i<n; i++)

    {

        scanf("%d",&array[i]);

    }

    quicksort(array,0,n-1);  /// call the quick sort function

    printf("Your Sorted Array: ");

    for(i=0; i<n; i++)

    {

        printf("%d ",array[i]);

    }

    printf("");

    return 0;

}

Output

Please Enter Array Size: 5


Please Enter Array Element: 1 9 0 3 6


Your Sorted Array: 0 1 3 6 9

Join the discussion

Add your comment