您的位置:首页 > 其它

快速排序

2015-07-31 15:44 302 查看
<pre name="code" class="cpp">#include "stdafx.h"
#include <iostream>
#include <stdio.h>
//快速排序
void improveqsort(int *list,int m,int n)
{
int k,t,i,j;
/*for(i=0;i<10;i++)
printf("%3d",list[i]);*/
if(m<n)
{
i=m;
j=n+1;
k=list[m];
while(i<j)
{
for(i=i+1;i<n;i++)
if(list[i]>=k)
break;
for(j=j-1;j>m;j--)
if(list[i]<=k)
break;
if (i<j)
{
t=list[i];
list[i]=list[j];
list[j]=t;
}
}
t=list[m];
list[m]=list[j];
list[j]=t;
improveqsort(list,m,j-1);
improveqsort(list,i,n);
}
}

int _tmain(int argc, _TCHAR* argv[])
{
int list[10];
int n=9,m=0,i;
printf(" input 10 number: ");
for (i=0;i<10;i++)
scanf("%d",&list[i]);
printf("\n");
improveqsort(list,m,n);
for (i=0;i<10;i++)
printf("%5d",list[i]);
printf("\n");
return 0;
}



<pre name="code" class="cpp">#include "stdafx.h"
#include <iostream>

using namespace std;

void Qsort(int a[], int low, int high)
{
if(low >= high)
{
return;
}
int first = low;
int last = high;
int key = a[first];/*用字表的第一个记录作为枢轴*/

while(first < last)
{
if(first < last && a[last] >= key)
{
--last;
}

a[first] = a[last];/*将比第一个小的移到低端*/

if(first < last && a[first] <= key)
{
++first;
}

a[last] = a[first];
/*将比第一个大的移到高端*/
}
a[first] = key;/*枢轴记录到位*/
Qsort(a, low, first-1);
Qsort(a, first+1, high);
}
int main()
{

int a[]={34,23,4,5,56,7,87,8,8,89,9,34,556,66,76};
Qsort(a,0,sizeof(a)/sizeof(a[0])-1);
for (int i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
cout<<a[i]<<" ";
}
cout<<endl;

//Qsort(a, 0, sizeof(a) / sizeof(a[0]) - 1);/*这里原文第三个参数要减1否则内存越界*/

//for(int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
//{
//	cout << a[i] << " ";
//}

return 0;
}/*参考数据结构p274(清华大学出版社,严蔚敏)*/



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: