int count = 0; void swap(int& a, int& b) { int c = a; a = b; b = c; //count++; cout << count++ << ":" << a << "<->" << b << endl; } void quickSort(int array[], int left, int right) { if (left >= right) { //cout << "ret" << endl; return; } int i, j, p; int temp=0; p = left; i = p+1; j = right; while (i <= j && i <= right && j>=left) { while (array[p] > array[i] && i <= right) { i++; } if (i > right) { swap(array[left], array[right]); p = right; break; } while (array[p] < array[j]) { j--; } if (j <= left) { p = left; break; } if (i >= j) { break; } swap(array[i], array[j]); i++; j--; } if (p != j) { swap(array[p], array[j]); p = j; } quickSort(array, left, p-1); quickSort(array, p+1, right); } 递归主要是分析出需要的变量,比如快速排序每次需要数组,左值,右值 还需要退出条件,比如左值不能大于等于右值。 测试用随机数组产生函数,一遍循环就可以得到不重复的随机数组 void random_shuffle(int array[], int n) { int r; for (int i=0; i<n-1; i++) { r = rand()%(n-1-i); //cout << n-1-i << "-" << r << endl; swap_rand(array[n-1-i], array[r]); } //swap_rand(array[0], array[array[0]]); }