标签:
#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