Saturday, 12 March 2016

Algorithm 6.8 (Quick Sort (recursive way) )


Before seeing the solution make sure that you tried enough. Don’t paste the whole code, just find out the logic. If you stuck in trouble, just inform me on comment.

/**Bismillahir Rahmanir Rahim.**/

#include <stdio.h>

int ara[500];

void q_sort(int frst, int lst);

int main()
{
    int i, n;
    printf("How many element you want to sort?\n");
    scanf("%d", &n);
    printf("Print %d element.\n", n);
    for(i=0; i<n; i++) scanf("%d", &ara[i]);

    q_sort(0, n-1);

    for(i=0; i<n; i++) printf("%d   ", ara[i]);
    printf("\n\n");
    return 0;
}
void q_sort(int frst, int lst)
{
    int loc, fixed, x, y;
    loc = frst;
    fixed = ara[frst];
    x = frst;
    y = lst;

    if(frst < lst)
    {
        while(x < y)
        {
            while(ara[y]>=fixed && loc<y) y--;
            if(ara[y] < fixed)
            {
                ara[loc] = ara[y];
                ara[y] = fixed;
                loc = y;
            }
            while(ara[x]<fixed && x<loc) x++;
            if(ara[x] >= fixed)
            {
                ara[loc] = ara[x];
                ara[x] = fixed;
                loc = x;
            }
        }
        q_sort(frst, loc-1);
        q_sort(loc+1, lst);
    }
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.