本題要求實現快速排序的一趟劃分函數,待排序列的長度1<=n<=1000。
函數接口定義:
int Partition ( SqList L,int low, int high );
其中L是待排序表,使排序後的數據從小到大排列。
類型定義:
typedef int KeyType;
typedef struct {
KeyType *elem; /*elem[0]一般作哨兵或緩衝區*/
int Length;
}SqList;
裁判測試程序樣例:
#include<stdio.h>
#include<stdlib.h>
typedef int KeyType;
typedef struct {
KeyType *elem; /*elem[0]一般作哨兵或緩衝區*/
int Length;
}SqList;
void CreatSqList(SqList *L);/*待排序列建立,由裁判實現,細節不表*/
int Partition ( SqList L,int low, int high );
void Qsort ( SqList L,int low, int high );
int main()
{
SqList L;
int i;
CreatSqList(&L);
Qsort(L,1,L.Length);
for(i=1;i<=L.Length;i++)
{
printf("%d ",L.elem[i]);
}
return 0;
}
void Qsort ( SqList L,int low, int high )
{ int pivotloc;
if(low<high)
{
pivotloc = Partition(L, low, high ) ;
Qsort (L, low, pivotloc-1) ;
Qsort (L, pivotloc+1, high );
}
}
/*你的代碼將被嵌在這裏 */
輸入樣例:
第一行整數表示參與排序的關鍵字個數。第二行是關鍵字值 例如:
10
5 2 4 1 8 9 10 12 3 6
輸出樣例:
輸出由小到大的有序序列,每一個關鍵字之間由空格隔開,最後一個關鍵字後有一個空格。
1 2 3 4 5 6 8 9 10 12
代碼:
int Partition(SqList L, int low, int high) {
int i = low, j = high;
int temp = L.elem[low],t;
while (i < j) {
while (i < j&&temp <= L.elem[j]){
j--; printf("j = %d\n",j);
}
L.elem[i]=L.elem[j];
printf("temp = %d\n",temp);
while (i < j&&L.elem[i] <= temp){
i++; printf("i = %d\n",i);
}
L.elem[j]=L.elem[i];
}
L.elem[i]=temp;
return i;
}
一趟劃分的圖解
這樣得到pivotloc,然後再執行分治函數