Quick sort int array into increasing order - C Data Structure

C examples for Data Structure:Sort

Description

Quick sort int array into increasing order

Demo Code

#include <stdio.h>
/* swap:  interchange v[i] and v[j] */
void swap(int v[], int i, int j)
{
    int temp;/*from  ww w  .j ava 2  s  .c o m*/

    temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}
/* qsort:  sort v[left]...v[right] into increasing order */
void qsort(int v[], int left, int right)
{
    int i, last;
    void swap(int v[], int i, int j);

    if (left >= right)   /* do nothing if array contains */
        return;          /* fewer than two elements */
    swap(v, left, (left + right)/2); /* move partition elem */
    last = left;                     /* to v[0] */
    for (i = left+1; i <= right; i++){
        if (v[i] < v[left])
            swap(v, ++last, i);
    }
    swap(v, left, last);         /* restore partition elem */
    qsort(v, left, last-1);
    qsort(v, last+1, right);
}

int main()
{
    int i, n, in[10];
    void qsort(int v[], int left, int right);

    n = 0;
    while (scanf("%d", &in[n]) != EOF)
        n++;
    qsort(in, 0, n-1);
    for (i = 0; i < n; i++)
        printf("%d\n", in[i]);
    return 0;
}

Result


Related Tutorials