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]; 6.2
do O(nlog2n)
{ O(nlog2n)
while( a[m]<k && m<j )
m++;
while( a[n] >k && n>i ) 6.3
n--;
if(m<=n) #include <stdio.h>
void Swap(int *, int *); //函数声明, 交换两个变量的值
void QuickSort(int *, int, int); //函数声明, 快速排序
int main(void)
{
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)
{ {
temp=a[m]; printf("%d ", a[i]);
a[m]=a[n];
a[n]=temp;
m++;
n--;
} }
printf("\n");
return 0;
} }
while(m<=n); void Swap(int *p, int *q)
{
if(m<j) int buf;
quick(a,m,j); buf = *p;
*p = *q;
if(n>i) *q = buf;
quick(a,i,n); 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