教科书的快速排序算法
int partition(int numbers[] ,int first,int end)
{
int i = first,j = end;
int piov = numbers[first];
while(i < j)
{
while(i < j && numbers[j] >= piov) j--;
numbers[i] = numbers[j];
while(i < j && numbers[i] <= piov) i++;
numbers[j] = numbers[i];
}
numbers[i] = piov;
return i;
}
int quicksort(int numbers[],int first, int end)
{
/* ensure two elements in array */
if(first < end - 1)
{
int pivot = partition(numbers,first,end);
quicksort(numbers,first,pivot);
quicksort(numbers,pivot + 1, end);
}
}
int main()
{
int a[] = {9,5,4,6,8,0,1,3,2,7};
quicksort(a,0,9);
int len = sizeof(a)/sizeof(a[0]);
while(len--)
{
printf("%d ",a[len]);
}
}
剑指offer的快速排序算法
算法的主要思路是,选随机选取一个介于数组长度与0之间的数,然后以这个数为基准,数组左边的小于这个数,数组右边的数都大于这个数。递归下去就可以把整个数组排序。
#include <iostream>
using namespace std;
int partition(int numbers[],int start,int end,int length)
{
if(numbers == NULL || start <0 || end > length)
{
return -1;
}
int index = RandonInRange(start,end);
Swap(&numbers[index],&numbers[end]);
int small = -1;
for(index = 0; index < end;index++)
{
if(numbers[index] < numbers[end])
{
++small;
if(small != index)
{
Swap(&numbers[small],&numbers[index]);
}
}
}
++small;
Swap(&numbers[small],&numbers[end]);
return small;
}
void quicksort(int numbers[],int start,int end,int length)
{
if(start == end)
return
int index = partiton(numbers,start,end,length);
if(index > start)
partition(numbers,start,index,length);
if(index < end)
partition(numbers,index + 1, end,length);
}