题目描述
According to the basic idea of quick sort algorithm descirbed on class, we will modify a little bit of this algorithm.
Only the first pivot is given by the input operation. The other pivots will still use Median-of-Three patitioning method.The inithial sequence is {49,38,65,97,76,13,27,50,2,8}. We will sort this sequence in ascending order.
The parameter Cutoff is 3.
输入格式:
The index of first pivot in the sequence. The index begins from 0.
输出格式:
Several lines. Each line shows the temporary result of sort.
In each interation, if the quicksort method is used, then add "Qsort:" before the result. The first number in bracket is the left index of sequence processed by quick sort method, and the second number is the right index of this sequence.
If the insertion sort method is used, then add "Insert:" before the result. The first number in brackets is the left index of sequence processed by insertion sort method, and the second number means the amount of the following elements.
Add "\n" to the end of each line.
输入样例:
在这里给出一组输入。例如:
1
输出样例:
在这里给出相应的输出。例如:
Qsort(0,9):2,8,27,13,38,97,65,50,49,76,
Qsort(0,3):2,8,27,13,38,97,65,50,49,76,
insert(0,1):2,8,27,13,38,97,65,50,49,76,
insert(2,2):2,8,13,27,38,97,65,50,49,76,
Qsort(5,9):2,8,13,27,38,50,65,49,76,97,
insert(5,3):2,8,13,27,38,49,50,65,76,97,
insert(9,1):2,8,13,27,38,49,50,65,76,97,
C语言代码
#include<stdio.h>
#include<stdlib.h>
#define CUTOFF 3
void Swap(int * a,int * b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void printstring(int *A){
int i;
for(i=0;i<10;i++){
printf("%d,",A[i]);
}
printf("\n");
}
void Insertionsort(int * A, int N){
int P,i;
for(P=1;P<N;P++){
int temp=A[P];
for(i=P;i>0;i--){
if(temp<A[i-1]) A[i]=A[i-1];
else break;
}
A[i]=temp;
}
}
int Median3(int * A,int Left, int Right){
int Center=(Left+Right)/2;
if(A[Left]>A[Center]) Swap(&A[Left],&A[Center]);
if(A[Left]>A[Right]) Swap(&A[Left],&A[Right]);
if(A[Center]>A[Right]) Swap(&A[Center],&A[Right]);
Swap(&A[Center],&A[Right-1]);
return A[Right-1];
}
void Qsort(int * A, int Left,int Right){
int i,j;
int Pivot;
if(Left+CUTOFF<=Right){
Pivot=Median3(A,Left,Right);
for(i=Left,j=Right-1;;){
while(A[++i]<Pivot){}
while(A[--j]>Pivot){}
if(i<j) Swap(&A[i],&A[j]);
else break;
}
Swap(&A[i],&A[Right-1]);
printf("Qsort(%d,%d):",Left,Right);
printstring(A);
Qsort(A,Left,i-1);
Qsort(A,i+1,Right);
}
else {
printf("insert(%d,%d):",Left,Right-Left+1);
Insertionsort(A+Left,Right-Left+1);
printstring(A);
}
}
void quicksort(int * A,int i_pivot){
Swap(&A[i_pivot],&A[9]);
int i,j,Pivot;
Pivot=A[9];
for(i=-1,j=9;;){
while(A[++i]<Pivot){}
while(A[--j]>Pivot){}
if(i<j) Swap(&A[i],&A[j]);
else break;
}
Swap(&A[i],&A[9]);
printf("Qsort(0,9):");
printstring(A);
Qsort(A,0,i-1);
Qsort(A,i+1,9);
}
main(){
int A[10]={49,38,65,97,76,13,27,50,2,8};
int pivot;
scanf("%d",&pivot);
quicksort(A,pivot);
return 0;
}