Skip to content

Commit db4de75

Browse files
committed
增加了随机选取枢轴元素的代码
1 parent ff0a972 commit db4de75

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

各种排序/快速排序/QuickSort.cpp

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@ Email:[email protected]
55
********************************/
66
#include<stdio.h>
77
#include<stdlib.h>
8+
#include<time.h>
89

910
void Quick_Sort(int *,int,int);
1011
int findPoss(int *,int,int);
1112
int Patrition(int *,int,int);
13+
int Random_Partition(int *,int,int);
1214
void swap(int *,int *);
1315

1416
int main()
@@ -43,7 +45,7 @@ void Quick_Sort(int *a,int low,int high)
4345

4446
if(low < high)
4547
{
46-
pos = Patrition(a,low,high);
48+
pos = Random_Partition(a,low,high);
4749
Quick_Sort(a,low,pos-1); //左边子序列排序
4850
Quick_Sort(a,pos+1,high); //右边子序列排序
4951
}
@@ -79,7 +81,7 @@ int findPoss(int *a,int low,int high)
7981
/*
8082
算法导论版快速排序
8183
*/
82-
int Patrition(int *a,int low ,int high)
84+
int Partition(int *a,int low ,int high)
8385
{
8486
if(a==NULL || low>high)
8587
return -1;
@@ -100,6 +102,18 @@ int Patrition(int *a,int low ,int high)
100102
return small;
101103
}
102104

105+
/*
106+
随机选取枢轴元素
107+
*/
108+
int Random_Partition(int *A,int low,int high)
109+
{
110+
//设置随机种子
111+
srand((unsigned)time(0));
112+
int index = low + rand()%(high-low+1);
113+
swap(&A[index],&A[high]);
114+
return Partition(A,low,high);
115+
}
116+
103117

104118
void swap(int *a,int *b)
105119
{

0 commit comments

Comments
 (0)