码迷,mamicode.com
首页 > 编程语言 > 详细

快速排序

时间:2015-02-24 21:06:54      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <stdlib.h>

void swap(int *i, int *j);
int choose_pivot(int i, int j);
int partition(int list[], int m, int n);
void quicksort(int list[], int m, int n);
void display(int list[], const int n);
const int SIZE = 10;

int main()
{
    int list[SIZE];

    int i = 0;
    for (i = 0; i < SIZE; ++i) {
        list[i] = rand();
    }

    printf("the list before sorting is: \n");
    display(list, SIZE);

    quicksort(list, 0, SIZE-1);

    printf("the list after sorting is: \n");
    display(list, SIZE);

    return 0;
}

void swap(int *i, int *j)
{
    int temp;

    temp = *i;
    *i = *j;
    *j = temp;
}

int choose_pivot(int i, int j)
{
    return (i+j)/2;
}

int partition(int list[], int m, int n)
{
    int pivot;
    int pivotkey;

    pivot = choose_pivot(m, n);
    swap(&list[m], &list[pivot]);
    pivotkey = list[m];

    while (m < n) {
        while ( (m < n) && (list[n] >= pivotkey) )
            n--;
        if (m < n) {
            list[m++] = list[n];
        }

        while ( (m < n) && (list[m] < pivotkey) )
            m++;
        if (m < n) {
            list[n--] = list[m];
        }
    }
    list[m] = pivotkey;

    pivot = m;
    return pivot;
}
void quicksort(int list[], int m, int n)
{
    int pivot;
    if (m < n) {
        pivot = partition(list, m, n);
        quicksort(list, m, pivot-1);
        quicksort(list, pivot+1, n);
    }
}

void display(int list[], const int n)
{
    int i;
    for(i = 0; i < n; ++i) {
        printf("%d\t", list[i]);
    }
}


the list before sorting is:
41      18467   6334    26500   19169   15724   11478   29358   26962   24464
the list after sorting is:
41      6334    11478   15724   18467   19169   24464   26500   26962   29358

Process returned 0 (0x0)   execution time : 0.042 s
Press any key to continue.



快速排序

标签:

原文地址:http://my.oschina.net/kimiz/blog/379762

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!