排序算法----快速排序(数组形式)
生活随笔
收集整理的這篇文章主要介紹了
排序算法----快速排序(数组形式)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這個快速排序主要利用遞歸調用,數組存儲方式。包含3個文件,頭文件QuickSort.h,庫函數QuickSort.c,測試文件TestQuickSort。
其中Cutoff可以自己給定,這個當開始給定的數組(或者遞歸調用產生的子數組)的元素個數<=20個時,采用插入排序。一般認為當元素個數<=20時,插入排序更快。這個20不是固定的,在這附近浮動都可以的。
頭文件QuickSort.h
1 #ifndef QuickSort_H 2 #define QuickSort_H 3 #define Cutoff 20 4 typedef float ElementType; 5 ElementType Median3(ElementType A[], int left, int right); 6 void Swap(ElementType *p, ElementType*q); 7 void InsertionSort(ElementType A[], int N); 8 void QuickSort(ElementType A[], int N); 9 void Qsort(ElementType A[], int Left, int Right); 10 void PrintMatrix(ElementType A[], int N); 11 12 #endif // !QuickSort_H?
庫函數QuickSort.c
1 #include "QuickSort.h" 2 #include<stdio.h> 3 //通過三數中值分割法獲得數組的樞紐元 4 ElementType Median3(ElementType A[], int Left, int Right) 5 { 6 int Center = (Left + Right) / 2; 7 if (A[Left] > A[Right]) 8 Swap(&A[Left], &A[Right]); 9 if (A[Left] > A[Center]) 10 Swap(&A[Left], &A[Center]); 11 if (A[Center] > A[Right]) 12 Swap(&A[Center], &A[Right]); 13 //上述三次交換使得:A[Left]<A[Center]<A[Right] 14 Swap(&A[Center], &A[Right - 1]); 15 return A[Right - 1];//返回樞紐元; 16 } 17 18 //交換指針p和q各自指向的值; 19 void Swap(ElementType * p, ElementType * q) 20 { 21 ElementType Tmp; 22 Tmp = *p; 23 *p = *q; 24 *q = Tmp; 25 } 26 27 //當開始給定的數組(或者遞歸調用產生的子數組)的元素個數<=20個時,采用插入排序。 28 void InsertionSort(ElementType A[], int N) 29 { 30 int j, P; 31 ElementType Tmp; 32 for (P = 1; P < N; P++) 33 { 34 Tmp = A[P]; 35 for (j = P; j > 0 && A[j - 1] > Tmp; j--) 36 A[j] = A[j - 1]; 37 A[j] = Tmp; 38 } 39 } 40 41 //快速排序算法驅動程序 42 void QuickSort(ElementType A[], int N) 43 { 44 Qsort(A, 0, N - 1); 45 } 46 47 //快速排序核心算法 48 void Qsort(ElementType A[], int Left, int Right) 49 { 50 int i,j; 51 ElementType Pivot; 52 if (Left + Cutoff-1 <= Right)//此處Cutoff-1是為了和N-1=Right對應上 53 { 54 Pivot = Median3(A, Left, Right);//調用樞紐元函數選取樞紐元 55 i = Left; j = Right - 1; 56 for (; ;) 57 { 58 while (A[++i] < Pivot); 59 while (A[--j] > Pivot); 60 if (i < j) Swap(&A[i], &A[j]); 61 else break; 62 } 63 Swap(&A[i], &A[Right - 1]); 64 Qsort(A, Left, i - 1);//對剩下小于樞紐元的元素遞歸排序 65 Qsort(A, i + 1, Right);//對剩下大于樞紐元的元素遞歸排序 66 } 67 else//當最后子數組只有Cutoff個,則采用插入排序。 68 InsertionSort(A + Left, Right - Left + 1); 69 } 70 71 //打印數組 72 void PrintMatrix(ElementType A[], int N) 73 { 74 for (int i = 0; i < N; i++) 75 printf("%f ", A[i]); 76 }?
測試文件TestQuickSort
1 #include "QuickSort.h" 2 #include <stdio.h> 3 #include<time.h> 4 #include<stdlib.h> 5 #define N 100000 6 int main() 7 { 8 ElementType A[N]; 9 srand((unsigned)time(NULL)); 10 for (int i = 0; i < N; i++) 11 A[i] = (float)(rand() % N)/N; 12 //printf("原始數組:\n"); 13 //PrintMatrix(A, N); 14 QuickSort(A, N); 15 printf("\n"); 16 printf("排序后數組:\n"); 17 PrintMatrix(A, N); 18 printf("\n"); 19 }隨機生成100000個浮點型數據,調用QuickSort算法進行快速排序,速度極快。
?
轉載于:https://www.cnblogs.com/xinlovedai/p/6229555.html
總結
以上是生活随笔為你收集整理的排序算法----快速排序(数组形式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于readdir返回值中struct
- 下一篇: 关于LoginFilter的问题