快速排序的随机化算法

来源:互联网 发布:淘宝黑色锁骨链 编辑:程序博客网 时间:2024/06/05 09:27
//快速排序的随机化算法#include <stdio.h>#include <stdlib.h>#define N 10//Exchange the valuevoid swap(int *p,int *q){int temp;temp=*p;*p=*q;*q=temp;}//generate a random number between p and qint random(int p,int q){int result=p+rand()%(q-p+1);return result;}//patitionint partition(int A[],int p,int q){int j=p,i=j-1,temp;;int r=A[q];for(int k=p;k<q;k++){if(A[k]<=r){i=i+1;temp=A[i];A[i]=A[k];A[k]=temp;}}temp=A[i+1];A[i+1]=A[q];A[q]=temp;return i+1;}//random_partitionint random_partition(int A[],int p,int q){int i=random(p,q);swap(&A[i],&A[q]);return partition(A,p,q);}//randomized_quicksortvoid randomized_quicksort(int A[],int p,int q){int r;if(p<q){r=random_partition(A,p,q);randomized_quicksort(A,p,r-1);randomized_quicksort(A,r+1,q);}}int main(){int A[N],i;for(i=0;i<N;++i)scanf("%d",&A[i]);randomized_quicksort(A,0,9);for(i=0;i<N;++i)printf("%d ",A[i]);printf("\n");}


原创粉丝点击