欢迎关注博主的公众号:happyGirl的异想世界。有更多干货还有技术讨论群哦~
三种方法的实现
#include<iostream>
using namespace std;
void quickSort(int a[],int,int);
void quickSort(int s[], int l, int r)//快排
{
if (l< r)
{
int i = l, j = r, x = s[l];
while (i < j)
{
while(i < j && s[j]>= x) j--; // 从右向左找第一个小于x的数
if(i < j) s[i++] = s[j];
while(i < j && s[i]< x) i++;// 从左向右找第一个大于等于x的数
if(i < j) s[j--] = s[i];
}
s[i] = x;
quickSort(s, l, i - 1); // 递归调用
quickSort(s, i + 1, r);
}
}
void select(int s[],int N)//选择法,从大到小
{
for(int i=0;i<N-1;i++)
{
int k=i;
for(int j=i+1;j<N;j++)
{
if(s[k]<s[j])k=j;
}
if(k!=i)
{
int t=s[i];
s[i]=s[k];
s[k]=t;
}
}
}
void bubble(int s[],int N)//冒泡法,从大到小
{
for(int i=0;i<N-1;i++)
{
int flag=0;
for(int j=0;j<N-i-1;j++)
{
if(s[j]<s[j+1])
{
int t=s[j];s[j]=s[j+1];s[j+1]=t;
flag=1;
}
}
if(flag==0)break;
}
}
int main()
{
int array[]={34,65,12,43,67,5,78,10,3,70},k;
int len=sizeof(array)/sizeof(int);
cout<<"The orginal arrayare:"<<endl;
for(k=0;k<len;k++)
cout<<array[k]<<",";
cout<<endl;
// quickSort(array,0,len-1);
// select(array,len);
bubble(array,len);
cout<<"The sorted arrayare:"<<endl;
for(k=0;k<len;k++)
cout<<array[k]<<",";
cout<<endl;
system("pause");
return 0;
}
快速排序:
int Partition(SqList &L, int low, int high)
{ L.r[0]=L.r[low];
pivotkey = L.[low].key;
while (low<high)
{ while (low<high&&L.r[high].key >= pivotkey) --high;
L.r[low] = L.r[high];
while (low<high&&L.r[low].key <= pivotkey)++low;
L.r[high]= L.r[low];
}
L.r[low] =L.r[0];
return low;
}
//数据结构C语言版 清华大学出版社P274算法10.6(b)