C program to implement quick sort

Algorithm:


1. Initialize last element as pivot.
2. Take two counter variables i and j, and start looping from 1st to last element   using i counter. Initialize j to 0.
    i.e. i = 0 to n-1; j = 0;
3. Swap ith element with jth element if it's less than pivot.
    increment j.
4. Swap jth element with ith element if i = n-1.
5. Recursively call
    quicksort(low, array, j-1)
    quicksort(j, array, high)    until low < high.

Program:

#include<stdio.h>

int quick_sort(int low, int array[], int high)
{
    int pivot, mid, temp, i=low, j=low, k;
    pivot = array[high-1];
    if (low < high)
    {
        for(i=low; i<high; i++)
        {
            if(array[i] < pivot || i == high-1)
            {
                temp = array[j];
                array[j] = array[i];
                array[i] = temp;
                j++;
            }
        }
        quick_sort(low, array, j-1);
      
        quick_sort(j, array, high);   
      
    }
   
}

int main()
{
    int num, i, j;
    printf("Enter the size of array: \n");
    scanf("%d", &num);
    int array[num];
    printf("Enter %d elements: \n",num );
    for (i = 0; i < num; ++i)
    {
        scanf("%d", &array[i]);
    }
    quick_sort(0, array, num);
    printf("\nsorted array: ");
    for (i = 0; i < num; ++i)
    {
        printf("%d ", array[i]);
    }
    printf("\n");
}

Output:

 

Comments

  1. Baccarat Online | Baccarat For Real Money - Spielione
    Baccarat is one of the most popular casino games. In the US, there is an online version 바카라 사이트 of Baccarat where 1xbet korean players wager on the outcome of a 샌즈카지노 round of

    ReplyDelete

Post a Comment

Popular Posts