quicksort

 1 template <class T>

 2 void quicksort(T *A ,int left, int right){

 3     T temp,a=A[right];

 4     int i=left-1,j=right;

 5     do{

 6         do i++;

 7         while(i<right&&A[i]<a);

 8         do j--;

 9         while(j>left&&A[j]>a);

10         if(i<j)

11         {    temp=A[i];

12             A[i]=A[j];

13             A[j]=temp;

14         }

15 

16     }while(i<j);

17 

18     temp=A[right];

19     A[right]=A[i];

20     A[i]=temp;    

21 

22 if(i-1>left)

23     quicksort(A,left,i-1);

24 if(i+1<right)

25     quicksort(A,i+1,right);

26 

27 }

 

 1 #include <iostream>

 2 #include <time.h>

 3 #include <stdlib.h>

 4 using namespace std;

 5 void Insertsort(int list[],int a,int b){

 6     int next,j;

 7     if(a>b)return;

 8     for(int x=a;x<=b;x++){

 9     next=list[x];

10     for(j=x-1;j>=a&&next<list[j];j--)

11         list[j+1]=list[j];

12     list[j+1]=next;

13     }

14 

15 }

16 

17 void quicksort(int list[],int left,int right)

18 {

19  int pivot,i,j;

20  int temp,pos;

21  //k取值为10

22  if(right-left<10){Insertsort(list,left,right);}else

23  if(left<right)

24  {//注明:在实现过程中,采用i,j从两边向中间遍历的方法,可进一步提高算法的速度

25   i=left;

26   j=right+1;

27   pos=rand()%(right-left)+left;//采用随机方法

28  pivot=list[pos];

29   temp=list[left];

30   list[left]=list[pos];

31   list[pos]=temp;

32 //pos =left;

33   do

34   {

35    do i++;

36    while(list[i]<pivot);

37  

38    

39    do j--;

40    while(list[j]>pivot);

41    if(i<j)

42    {temp=list[i];

43    list[i]=list[j];

44    list[j]=temp;}

45   }while(i<j);

46 

47   temp=list[left];

48   list[left]=list[j];

49   list[j]=temp;

50   quicksort(list,left,j-1);

51   quicksort(list,j+1,right);

52  }

53  else return;

54 }

55 

56 int main()

57 {

58  int i;

59  int n=1000000;

60  int list[1000000];

61 

62  srand((unsigned)time(NULL));

63  for(i=0;i<n;i++)

64  list[i]=rand();

65 

66  quicksort(list,0,n-1);

67 // for(i=0;i<n;i+=20)

68 // cout<<" "<<list[i];

69 

70  return 0;  

71 }

 

你可能感兴趣的:(Quicksort)