Update 快速法.cpp

master
pmkfqw2gu 4 years ago
parent ab2430c996
commit 181596a9b9

@ -1,35 +1,76 @@
6.
6.1
oid quick(int *a,int i,int j)
{
int m,n,temp;
int k;
m=i;
n=j;
k=a[(i+j)/2];
do
{
while( a[m]<k && m<j )
m++;
使listsub-lists
1 pivot
2
退partition
3recursive
while( a[n] >k && n>i )
n--;
6.2
O(nlog2n)
O(nlog2n)
if(m<=n)
{
temp=a[m];
a[m]=a[n];
a[n]=temp;
m++;
n--;
}
}
while(m<=n);
6.3
if(m<j)
quick(a,m,j);
#include <stdio.h>
void Swap(int *, int *); //函数声明, 交换两个变量的值
void QuickSort(int *, int, int); //函数声明, 快速排序
if(n>i)
quick(a,i,n);
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)
{
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