快速排序(quick sort)是一种最早由东尼·霍尔提出的一种排序算法,又简称快排简称快排。平均来说该算法所需的时间复杂度为O(nlog n)明显比其他的排序算法的时间复杂度要低,例如最简单的冒泡算法为O(n^2)。下面,小编将简单介绍一下该算法的实现步骤。
工具/原料
方法/步骤
1算法描述:1、选泉冲择中枢元素。可能是第一个元素、也可能是最后一个元素,也肯能是随机位置的元素。2、分割。将数组分成大于中枢元素和小中枢元素的两个区间,排列。3、递归地完成步骤1、2
2快速排序算法是一种应用了分而治之的思想(divide and conquer),其时间复杂度为:O(n*log n)
3举个例子示范:有一个未排序的数组:{1, 12, 5, 26, 7, 14, 3, 7, 2}.我们将使用快速排序的方法进行排序。
4选取中枢元素:在这个示例中我们选择中间位置的元素为中枢元素。(注意,也可以选择第一或者最后位置的元素为中枢元素)。
5分割。将小于中枢值的元素放在左边,大于中枢值的元素优先放在右边。采用分而治之的策略,递归地进行。
6代码如下,这里我们选择数组的最后一个元互央泉素作为中枢元素。#include using namespace std;void swap(int*x,int *y){ int t=*x; *x=*y; *y=t;}/*This function takes the last element as pivot,places the pivot at the correct position in sorted arrayand places the smaller element to the left of the pivotand the larger element to the right side*/int partition(int arr[],int low, int high){ int pivot =arr[high]; int i=low-1;//index of smaller element for (int j=low;j<=high-1;j++) { //if current element is smaller or equal to the pivot if (arr[j]<=pivot) { i++;//increment index of smaller element 毙英 swap(&arr[i],&arr[j]); } } swap(&arr[i+1],&arr[high]); return i+1;}/*This main function implements QuickSort.arr[] is array to be sortedlow is the starting indexhigh is the ending index*/void quicksort(int arr[],int low,int high){ if (low
注意事项