1. 程式人生 > >對動態陣列進行快速排序

對動態陣列進行快速排序

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
void swap(int&,int&);
int partion(int *a,int p,int r);
void QuickSort(int *a,int p,int r);
int main()
{
     int *array1 = 0, num, i; 
     printf("please input the number of element: "); 
     scanf("%d", &num); 


     // 申請動態陣列使用的記憶體塊 
     array1 = (int *)malloc(sizeof(int)*num); 
     if (array1 == 0)             // 記憶體申請失敗,提示退出 
     { 
         printf("out of memory,press any key to quit...\n"); 
         exit(0);             // 終止程式執行,返回作業系統 
     } 


     // 提示輸入num個數據 
      printf("please input %d elements: ", num); 
      for (i = 0; i < num; i++) 
         scanf("%d", &array1[i]); 


     // 輸出剛輸入的num個數據 
     printf("%d elements are: \n", num); 
     for (i = 0; i < num; i++) 
         printf("%d,", array1[i]); 
printf("\n");
QuickSort(array1,0,num-1);
printf("the sorted number is :\n");
for (i = 0; i < num; i++) 
         printf("%3d", array1[i]); 
    getchar();
getchar();
return 0;
}


void QuickSort(int *a,int low,int high)
{
    if (low<high){
        int q=partion(a,low,high);
        QuickSort(a,low,q-1);
        QuickSort(a,q+1,high);
    }
}
int partion(int *a,int low,int high)
{
int val=a[low];
while(low<high)
{
while(low<high && a[high]>=val)
--high;
a[low]=a[high];
while(low<high && a[low]<val)
++low;
a[high]=a[low];

}
a[low] = val; 
return high;
}