被传值传引用的问题还有一些杂事困扰了一下午,现在终于可以静下心来写博客了。
这个Partition函数是我在《剑指Offer》那本书上看到的,其实对应于快排是一个单项扫描。
这个函数在很多算法题上都有应用,主要原理就是选定一个参考值,然后将数据分成两部分,左边都是比它小的,右边都是比它大的。然后把中位数返回一下。
#include<iostream>
//#include<algorithm>
using namespace std;//这里实际上是定义了命名空间,如果不加这句话,之后用到的每一个函数都得加std::void Swap(int &a,int &b)
{
int c;
c=b;
b=a;
a=c;
}
int Partition(int a[],int length,int start,int end)
{
if(a==NULL && length<=0 && start<0 && end>=length)
//throw exception("Invalid Parameters");
return 0;
int index=start;
Swap(a[index],a[end]);
int small=start-1;
for(index=start;index<end;++index)
{
if(a[index]<a[end])
{
++small;
if(small!=index)
Swap(a[index],a[small]);
}
}
++small;
Swap(a[small],a[end]);
return small;
}
void Quicksort(int a[],int length,int start,int end)
{
if(start==end)
return;
int index=Partition(a,length,start,end);
if(start<index)
Quicksort(a,length,start,index-1);
if(end>index)
Quicksort(a,length,index+1,end);
}
void printdata(int a[],int length)
{
for(int i=0;i<length;i++)
{
cout<<a[i]<<endl;
}
}
int main()
{
int a[5]={4,2,1,5,2};
//int *b=new int[5];
Quicksort(a,5,0,4);
printdata(a,5);
int d=1;
int e=2;
Swap(d,e);
cout<<d;
}