week9 quick sort change to median3 method
This commit is contained in:
44
week9/T8.c
44
week9/T8.c
@@ -53,24 +53,46 @@ bool Check(int *A, int size) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void QuickSort(int *A, int left, int right) {
|
void QuickSort(int *A, int left, int right) {
|
||||||
|
int i, j;
|
||||||
|
int pivot;
|
||||||
|
|
||||||
if (left >= right) {
|
if (left >= right) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int pi = Partition(A, left, right);
|
|
||||||
QuickSort(A, left, pi - 1);
|
pivot = Median3(A, left, right);
|
||||||
QuickSort(A, pi + 1, right);
|
i = left;
|
||||||
|
j = right - 1;
|
||||||
|
|
||||||
|
while (1) {
|
||||||
|
while (A[++i] < pivot) {}
|
||||||
|
while (A[--j] > pivot) {}
|
||||||
|
if (i >= j) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Swap(&A[i], &A[right - 1]);
|
||||||
|
}
|
||||||
|
Swap(&A[i], &A[right - 1]);
|
||||||
|
|
||||||
|
QuickSort(A, left, i -1);
|
||||||
|
QuickSort(A, i + 1, right);
|
||||||
}
|
}
|
||||||
|
|
||||||
int Partition(int *A, int left, int right) {
|
int Median3(int *A, int left, int right) {
|
||||||
int pivot = A[right];
|
int center = (left + right) / 2;
|
||||||
int i = left - 1;
|
|
||||||
for (int j = left; j < right; j++) {
|
if (A[left] > A[center]) {
|
||||||
if (A[j] < pivot) {
|
Swap(&A[left], &A[center]);
|
||||||
Swap(&A[++i], &A[j]);
|
|
||||||
}
|
}
|
||||||
|
if (A[left] > A[right]) {
|
||||||
|
Swap(&A[left], &A[right]);
|
||||||
}
|
}
|
||||||
Swap(&A[++i], &A[right]);
|
if (A[center] > A[right]) {
|
||||||
return i;
|
Swap(&A[center], &A[right]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Swap(&A[center], &A[right - 1]);
|
||||||
|
return A[right - 1];
|
||||||
}
|
}
|
||||||
|
|
||||||
void HeapSort(int *A, int n) {
|
void HeapSort(int *A, int n) {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
void QuickSort(int *A, int left, int right);
|
void QuickSort(int *A, int left, int right);
|
||||||
|
|
||||||
int Partition(int *A, int left, int right);
|
int Median3(int *A, int left, int right);
|
||||||
|
|
||||||
void HeapSort(int *A, int n);
|
void HeapSort(int *A, int n);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user