以前写过的几种排序算法代码,贴上。
#include<iostream>
#include<malloc.h>
using namespace std;
//namespace Sort{
//选择排序[0,n)
void SelectSort(int n,int a[])
{
for(int i=0;i<n-1;i++)
{
int minIndex=i;
for(int j=i+1;j<n;j++)
{
if(a[minIndex]>a[j])
{
minIndex=j;
}
}
if(minIndex!=i)
{
int t=a[minIndex];
a[minIndex]=a[i];
a[i]=t;
}
}
}
//冒泡排序[0,n)
void BubuleSort(int n,int a[])
{
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
//合并排序[left,right)
void MergeSort(int *left,int *right){
int size=right-left;
if(size<=1){
return;
}
int *mid=left+size/2;
MergeSort(left,mid);
MergeSort(mid,right);
//开辟存储
int *p=(int *)malloc(size*sizeof(int));
int *p1=left;
int *p2=mid;
//合并
while(p1!=mid||p2!=right){
*p++=(p2==right||(p1!=mid&&(*p1)<(*p2)))?(*p1++):(*p2++);
}
p=p-size;//回到起点
p1=left;
//复制结果回来
while(p1!=right){
*p1++=*p++;
}
//释放存储
free(p-size);
}
//快速排序 [left,right](这里包括了right)
void quickSort2(int a[],int left,int right){
int i=left;
int j=right;
int p=(left+right)/2;
int t;
while(i<j){
while(i<=p&&a[i]<=a[p]){
i++;
}
if(i<p){
t=a[i];
a[i]=a[p];
a[p]=t;
p=i;
}
while(j>=p&&a[j]>=a[p]){
j--;
}
if(j>p){
t=a[j];
a[j]=a[p];
a[p]=t;
p=j;
}
}
if(left<p-1){
quickSort2(a,left,p-1);
}
if(right>p+1){
quickSort2(a,p+1,right);
}
}
//快速排序
//以a[l]为中心元素,把a[l~r)的元素分开,返回中心元素位置
int part(int a[],int l,int r)
{
int i=l+1;
int j=r-1;
while(1)
{
while(a[j]>a[l])
{
j--;
}
while(a[i]<a[l])
{
i++;
if(i>=r)
{
break;
}
}
if(i<j)
{
int t=a[i];
a[i]=a[j];
a[j]=t;
continue;
}
else
{
int t=a[j];
a[j]=a[l];
a[l]=t;
return j;
}
}
}
//快速排序 a[l~r)的元素
void QuickSort(int a[],int l,int r)
{
if(r-l<=1)
{
return;
}
int c=part(a,l,r);
QuickSort(a,l,c);
QuickSort(a,c+1,r);
}
int main()
{
int n;
int a[20000];
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
//选择排序
//cout<<"SelectSort"<<endl;
//SelectSort(n,a);
//cout<<"BubuleSort"<<endl;
//BubuleSort(n,a);
//cout<<"MergeSort"<<endl;
//MergeSort(a+0,a+n);
//cout<<"QuickSort"<<endl;
//QuickSort(a,0,n);
cout<<"QuickSort2"<<endl;
quickSort2(a,0,n-1);
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}