快速排序的随机化版本代码

来源:互联网 发布:练习打字的最好软件 编辑:程序博客网 时间:2024/05/16 12:58

之前写了快速排序算法,由于快速排序每次迭代总是用数组的最后一个值作为参考值,所以此算法的运行时间与数组的原始排序方式有关,所以在《算法导论》中介绍了快速排序的随机化版本,即每次从要排序的数组中随机选择一个作为参考值,这样算法就与原始排序方式无关。同样只贴出代码,原理请GOOLE,肯定比我讲的好多了。

#include "FastSort.h"#include <stdlib.h>int sortPartition(int array[],int p,int r){    int temp=0;    int q=rand()%(r-p);//在序号p~r之间随机挑选一个与array[r]交换    temp=array[p+q];    array[p+q]=array[r];    array[r]=temp;    q=p-1;    int i_ref = array[r];    for(int i=p;i<r;i++)    {        if(array[i]<=i_ref)        {            q++;            temp=array[i];            array[i]=array[q];            array[q]=temp;        }    }    temp=array[q+1];    array[q+1]=i_ref;    array[r]=temp;    return q+1;}void fastSort(int array[],int p,int r){    if(p>=r) return ;    int q=sortPartition(array,p,r);    fastSort(array,p,q-1);    fastSort(array,q+1,r);}#ifndef FASTSORT_H_INCLUDED#define FASTSORT_H_INCLUDEDvoid fastSort(int array[],int p,int r);int sortPartition(int array[],int p,int r);#endif // FASTSORT_H_INCLUDED

测试代码如下:

#include<stdio.h>#include<time.h>#include <stdlib.h>#include <string.h>//#include <malloc.h>#include "FastSort.h"#define num 5int array[num];int main(){  unsigned int a =0;  for(;a<num;a++)    array[a] = rand();  for(a=0;a<num;a++)    printf("%d、",array[a]);  printf("\n");   // divideProcessSort(array,0,num-1);  fastSort(array,0,num-1);  for(a=0;a<num;a++)    printf("%d、",array[a]);  return 0;}


0 0