算法学习(一)——快速排序
快速排序算法是对包含n个数的输入数组进行排序,算法的期望时间为θ(nlgn),最坏的运行时间为θ(n
2
),并且其使用就地排序。
举个例子 对数组A[p..r]排序可分成以下三个步骤:
分解:数组A[p..r]划分成A[p..q-1]和A[q+1..r],使得A[p..q-1]中的每个元素都小于等于A[q],而且小于等于A[q+1..r]中的元素;
解决:通过递归调用快速排序,对数组A[p..q-1]和A[q+1..r]进行排序;
合并:因为两个数组时就地排序,可以将它们直接合并
下面是快速排序的过程
QUICKSORT(A, p, r) if p < r then q ← PARTITION(A, p, r) QUICKSORT(A, p, q-1) QUICKSORT(A, q+1, r)
细化QUICKSORT(A, p, r)
PARTITION(A, p, r) x ← A[r] i ← p-1 for j ← p to r-1 do if A[j] <= x then i ← i+1 exchange A[i] ↔ A[j] exchange A[i+1] ↔ A[r] return i+1
官方经典快速排序算法
#include <stdlib.h> #include <stdio.h> #define NUM_ITEMS 100 void quickSort(int numbers[], int array_size); void q_sort(int numbers[], int left, int right); int numbers[NUM_ITEMS]; int main() { int i; //seed random number generator srand(getpid()); //fill array with random integers for (i = 0; i < NUM_ITEMS; i++) numbers[i] = rand(); //perform quick sort on array quickSort(numbers, NUM_ITEMS); printf("Done with sort.\n"); for (i = 0; i < NUM_ITEMS; i++) printf("%i\n", numbers[i]); } void quickSort(int numbers[], int array_size) { q_sort(numbers, 0, array_size - 1); } void q_sort(int numbers[], int left, int right) { int pivot, l_hold, r_hold; l_hold = left; r_hold = right; pivot = numbers[left]; while (left < right) { while ((numbers[right] >= pivot) && (left < right)) right--; if (left != right) { numbers[left] = numbers[right]; left++; } while ((numbers[left] <= pivot) && (left < right)) left++; if (left != right) { numbers[right] = numbers[left]; right--; } } numbers[left] = pivot; pivot = left; left = l_hold; right = r_hold; if (left < pivot) q_sort(numbers, left, pivot-1); if (right > pivot) q_sort(numbers, pivot+1, right); }