查看完整版本 : quick sort 問題

TonyKwan 2009-9-17 22:33

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
#define SWAP(x,y) {int t; t = x; x = y; y = t;}

void quicksort(int[], int, int);

int main(void) {
int number[MAX] = {0};
int i, num;

srand(time(NULL));

printf("排序前：");
for(i = 0; i < MAX; i++) {
number = rand() % 100;
printf("%d ", number);
}

quicksort(number, 0, MAX-1);

printf("\n排序後：");
for(i = 0; i < MAX; i++)
printf("%d ", number);

printf("\n");

return 0;
}

void quicksort(int number[], int left, int right) {
int i, j, s;

if(left < right) {
s = number[left];
i = left;
j = right + 1;

while(1) {
// 向右找
while(i + 1 < MAX && number[++i] < s) ;
// 向左找
while(j -1 > -1 && number[--j] > s) ;
if(i >= j)
break;
SWAP(number, number[j]);
}

number[left] = number[j];
number[j] = s;

quicksort(number, left, j-1);   // 對左邊進行遞迴
quicksort(number, j+1, right);  // 對右邊進行遞迴
}
}

quicksort(number, left, j-1);   // 對左邊進行遞迴
quicksort(number, j+1, right);  // 對右邊進行遞迴

PS : 呢套PROGRAM係成功SORT到野的

fitcat07 2009-9-18 11:06

[url]http://zh.wikipedia.org/zh-hk/%E9%81%9E%E8%BF%B4[/url]
[url]http://en.wikipedia.org/wiki/Recursion[/url]

softwarehouse 2009-9-18 11:09

[quote]原帖由 [i]TonyKwan[/i] 於 2009-9-17 22:33 發表 [url=http://www28.discuss.com.hk/redirect.php?goto=findpost&pid=222722300&ptid=10613631][img]http://www28.discuss.com.hk/images/common/back.gif[/img][/url]

PS : 呢套PROGRAM係成功SORT到野的[/quote]

TonyKwan 2009-9-18 15:06

hereticx2 2009-9-18 17:21

quicksort(number, left, j-1);   // 對左邊進行遞迴

TonyKwan 2009-9-18 18:04

:loveliness:

YjgfkHJj 2020-12-5 23:53

imagine a tree, first u call quicksort is like going up from the root, then in that function it call itself again, it is like generating a new branch, then in that new branch, it may do so again .... until it hit a stop case ... then the outermost branch function ends, return to its caller ... then its caller completes, return to its caller ... all the way up back to the root, then the program ends