Update 快速法.cpp

master
pmkfqw2gu 4 years ago
parent ab2430c996
commit 181596a9b9

@ -1,35 +1,76 @@
6. 6.
6.1 6.1
oid quick(int *a,int i,int j) 使listsub-lists
{ 1 pivot
int m,n,temp; 2
int k; 退partition
m=i; 3recursive
n=j;
k=a[(i+j)/2];
do
{
while( a[m]<k && m<j )
m++;
while( a[n] >k && n>i ) 6.2
n--; O(nlog2n)
O(nlog2n)
if(m<=n) 6.3
{
temp=a[m];
a[m]=a[n];
a[n]=temp;
m++;
n--;
}
}
while(m<=n);
if(m<j) #include <stdio.h>
quick(a,m,j); void Swap(int *, int *); //函数声明, 交换两个变量的值
void QuickSort(int *, int, int); //函数声明, 快速排序
if(n>i) int main(void)
quick(a,i,n); {
int i; //循环变量
int a[] = {22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70};
QuickSort(a, 0, 14);
printf("最终排序结果为:\n");
for (i=0; i<14; ++i)
{
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
void Swap(int *p, int *q)
{
int buf;
buf = *p;
*p = *q;
*q = buf;
return;
} }
void QuickSort(int *a, int low, int high)
{
int i = low;
int j = high;
int key = a[low];
if (low >= high) //如果low >= high说明排序结束了
{
return ;
}
while (low < high)
{
while (low < high && key <= a[high])
{
--high;
}
if (key > a[high])
{
Swap(&a[low], &a[high]);
++low;
}
while (low < high && key >= a[low])
{
++low;
}
if (key < a[low])
{
Swap(&a[low], &a[high]);
--high;
}
}
QuickSort(a, i, low-1); //用同样的方式对分出来的左边的部分进行同上的做法
QuickSort(a, low+1, j); //用同样的方式对分出来的右边的部分进行同上的做法
}
6.4
0.02485s

Loading…
Cancel
Save