自用快排 C语言
//劃分算法 嚴(yán)蔚敏版本
int Partition(int A[], int low, int high) {int pivot = A[low];//將當(dāng)前表紅第一個(gè)元素設(shè)為樞軸,對(duì)表進(jìn)行劃分while (low < high) {//跳出循環(huán)條件while (low < high && A[high] >= pivot) --high;A[low] = A[high];//將比樞軸小的元素移動(dòng)到左端while (low < high && A[low] <= pivot) ++low;A[high] = A[low];//將比樞軸大的元素移動(dòng)到右端}A[low] = pivot;return low;//返回存放樞軸的最終位置
}// 獲得三個(gè)數(shù)中的中間數(shù)
int getSecond(int A[],int a, int b, int c) {int max = A[a] > A[b] ? A[a] : A[b];max = max > A[c] ? max : A[c];int min = A[a] < A[b] ? A[a] : A[b];min = min < A[c] ? min : A[c];int second = A[a] + A[b] + A[c] - max - min;if (A[a] == second)return a;else if (A[b] == second)return b;else if (A[c] == second)return c;
}//劃分算法 改進(jìn)版本
int PartitionInproved(int A[], int low, int high) {int median = (low + high) / 2;int pivotNum = getSecond(A, low, high, median);int pivot = A[pivotNum];//將當(dāng)前表紅第一個(gè)元素設(shè)為樞軸,對(duì)表進(jìn)行劃分A[pivotNum] = A[low];while (low < high) {//跳出循環(huán)條件while (low < high && A[high] >= pivot) --high;A[low] = A[high];//將比樞軸小的元素移動(dòng)到左端while (low < high && A[low] <= pivot) ++low;A[high] = A[low];//將比樞軸大的元素移動(dòng)到右端}A[low] = pivot;return low;//返回存放樞軸的最終位置
}//快排
void QuickSort( int A[], int low, int high) {if (low < high) {//遞歸跳出條件//int pivotpos = PartitionInproved(A, low, high);//劃分 int pivotpos = Partition(A, low, high);//劃分/*printf(" Sort");for (int i = 0; i <= high; i++) {printf(" %d", A[i]);}printf("\n");*/QuickSort(A, low, pivotpos - 1);QuickSort(A, pivotpos + 1, high);}
}
?
總結(jié)
- 上一篇: matlab中求矩阵A的特征向量,mat
- 下一篇: 多语言开发插件CodeMix和Angul