quicksort

Holyjesus
mail@pastecode.io avatar
unknown
c_cpp
2 years ago
1.8 kB
3
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#define Maxsize 10

void quicksort(int *, int, int);
int partition(int *, int p, int r);

int i = 0, j = 0, k = 0, temp;

int main(){

int a[Maxsize], n, s;
    printf("\n 1.Enter the Array \n 2.Quick sort\n 3.Diplay the array \n 4.Exit");
    while (1)
    {
        printf("\n Enter your choice : ");
        scanf("%d", &s);
        switch (s)
        {

        case 1:

            printf("\n Enter the Number of Elements : ");
            scanf("%d", &n);
            printf("\n Enter the numbers :\n");
            for (i = 0; i < n; i++)
                scanf("%d", &a[i]);
            printf("\n Unsorted array elements are\n");
            for (i = 0; i < n; i++)
                printf("\t%d", *(a + i));
            break;
        case 2:
            printf("\n'Quick Sort'\n");
            quicksort(a, 0, n - 1);
            break;
        case 3:
            printf("\n Sorted array elements are\n");
            for (i = 0; i < n; i++)
                printf("\t%d", *(a + i));
            break;

        case 4:

            exit(0);
        }
    }
    return 0;
}

void quicksort(int *m, int p, int r)
{
    int q;
    if (p < r)
    {
        q = partition(m, p, r);
        quicksort(m, p, q - 1);
        quicksort(m, q + 1, r);
    }
}

int partition(int *m, int p, int r)
{
    k = *(m + p);
    i = p;
    j = r;
    while (i < j)
    {
        while (*(m + i) <= k)
            i++;
        while (*(m + j) > k)
            j--;
        if (i < j)
        {
            temp = *(m + i);
            *(m + i) = *(m + j);
            *(m + j) = temp;
        }
    }
    *(m + p) = *(m + j);
    *(m + j) = k;
    return j;
}