Signup/Sign In

C Program to Perform Quick Sort on a set of Entries using Recursion

learn c language tutorial

Logic To Perform Quick Sort On A Set Of Entries From A File Using Recursion:

  • The array to be sorted is defined, the array size is passed by the user
  • The algorithm checks if the 1st element is smaller than the last element,
  • The function partitioning is set to the last element of the array and defines variable increments, the same variable is used to partition the elements into sub-arrays,
  • After the partitioning, the function will be called continuously itself for sorting itself into sub-arrays,
  • Once arrays are sorted they will be printed.

Program To Perform Quick Sort On A Set Of Entries From A File Using Recursion:

#include <stdio.h>

void quicksort (int [], int, int);

int main()
{
    int list[100];
    int value, i;

    printf("Enter The Number Of Elements To Sort: ");
    scanf("%d", &value);

    printf("\nEnter The Elements To Sort: \n");

    for (i = 0; i < value; i++)
    {
         printf("\nEnter The [ %d ] Element: ",i+1);
        scanf("%d", &list[i]);
    }

    quicksort(list, 0, value - 1);

    printf("\n Implemented Quick Sort: \n\n");

    for (i = 0; i < value; i++)
    {
        printf("%d  ", list[i]);
    }

    printf("\n");

    return 0;
}

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

Output:

Quick



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight