Data Structure Quick Sort

Program of Quick Sort given below:

//Quick Sort program

#include <stdio.h>

void swap(int* x, int* y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}

int partition(int A[], int lb, int ub)
{
    int pivot = A[lb];
    int start = lb;
    int end = ub;
    while (start < end)
    {
        while (A[start] <= pivot)
        {
            start++;
        }
        while (A[end] > pivot)
        {
            end--;
        }
        if (start < end)
        {
            swap(&A[start], &A[end]);
        }
    }
    swap(&A[lb], &A[end]);
    return end;
}

void quicksort(int A[], int lb, int ub)
{
    if (lb < ub)
    {
        int loc = partition(A, lb, ub);
        quicksort(A, lb, loc - 1);
        quicksort(A, loc + 1, ub);
    }
}

void printArray(int array[], int size)
{
    for (int i = 0; i < size; ++i)
    {
        printf("%d  ", array[i]);
    }
    printf("\n");
}

int main()
{
    int n, A[50];
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    printf("Enter the array:\n");
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &A[i]);
    }
    printf("The unsorted array is:\n");
    printArray(A, n);
    quicksort(A, 0, n - 1);
    printf("The sorted array is:\n");
    printArray(A, n);

    return 0;
}

Output

Enter the size of the array: 9
Enter the array:
7 6 10 5 9 2 1 15 7
The unsorted array is:
7  6  10  5  9  2  1  15  7  
The sorted array is:
1  2  5  6  7  7  9  10  15 

Leave a Reply

Your email address will not be published. Required fields are marked *

Solverwp- WordPress Theme and Plugin