快速排序(Quick-Sort)
2017-11-02 22:22
363 查看
快速排序(Quick-Sort)
对于包含n个数的数组来说,快速排序是一种最坏情况下时间复杂度为O(n²)的排序算法。虽然最坏情况下的时间复杂度很差,但是快速排序通常是实际应用中最好的选择,因为它的平均性能非常好。下面是算法导论中给出的快速排序的伪代码:
QUICK-SORT(A,p,r)
if p < r
q = PARTITION(A,p,r)
QUICK-SORT(A,p,q - 1)
QUICK-SORT(A,q + 1,r)
PARTITION(A,p,r)
x = A[r]
i = p - 1
for j = p to r - 1
if A[j] <= x
i = i + 1
exchange A[i] with A[j]
exchange A[i + 1] with A[r]
return i + 1
下面是快速排序的Java实现:
/** * Created by CvShrimp on 2017/10/12. */ public class QuickSort { public static int partition(int[] array, int p, int r) { int i = p - 1; for(int j = p; j < r; j++) { if(array[j] <= array[r]) { i++; swapArrayElement(array, i, j); } } i++; swapArrayElement(array, i, r); return i; } public static void quickSort(int[] array, int p, int r) { if(p < r) { int q = partition(array, p, r); quickSort(array, p, q - 1); quickSort(array, p + 1, r); } } public static void swapArrayElement(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } public static void main(String[] args) { int[] array = {1,6,10,5,666,4,66,666}; QuickSort.quickSort(array, 0, array.length - 1); System.out.print("Sorted result: "); for(int temp : array) { System.out.print(temp + " "); } System.out.println(); } }
相关文章推荐
- 排序——快速排序(quick_sort)
- java quick sort(快速排序)
- 快速排序(quick-sort)
- 排序算法之快速排序(quick_sort)
- 算法导论——快速排序(Quick-Sort)
- 快速排序(Quick_Sort)
- 快速排序(Quick-Sort)
- Algorithm: quick sort implemented in python 算法导论 快速排序
- 快速排序的简单实现(Quick_Sort)
- 【数据结构笔记】快速排序(quick_sort)和快速选择(quick_select)--Python2.7
- 快速排序(quick_sort)
- 快速排序的简单实现(Quick_Sort)
- quick_sort(快速排序)c语言实现
- 排序_Quick_Sort(快速排序)
- 迭代的快速排序(Iterative Quick Sort)
- C标准库中的快速排序(quick-sort)函数 [简单应用]
- Insertion sort, select sort, Quick sort and Merge sort
- quick sort in golang
- 快速排序与快速选择算法(quick sort and quick select algorithm)
- Quick_Sort