这里主要涉及到的排序算法,包括冒泡排序、选择排序、直接插入排序、快速排序和哈希排序。这里先声明一下,下面的排序算法大多包含了三个输入参数:待排序的数组、数组的成员个数和flag标志,若flag的值为true则标志按照升序排列元素,flag为false则按照降序排列元素。
冒泡排序算法:
#include<iostream>
using namespace std;
typedef int DataType;
void BubSort(DataType a[],int n,bool flag)
{
int i,j;
DataType temp;
if(flag)
{
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
else
{
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]<a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
}
int main()
{
DataType a[10];
int i;
for(i=0;i<10;i++)
cin>>a[i];
//true表示升序排列,false表示降序排列
BubSort(a,10,false);
for(i=0;i<10;i++)
cout<<a[i]<<' ';
cout<<endl;
return 0;
}
选择排序算法:
#include<iostream>
using namespace std;
typedef int DataType;
void SelectSort(DataType a[],int n,bool flag)
{
int i,j,index;
DataType temp;
if(flag)
{
for(i=0;i<n;i++)
{
index=i;
for(j=i+1;j<n;j++)
{
if(a[index]>a[j])
index=j;
}
if(i!=index)
{
temp=a[index];
a[index]=a[i];
a[i]=temp;
}
}
}
else
{
for(i=0;i<n;i++)
{
index=i;
for(j=i+1;j<n;j++)
{
if(a[index]<a[j])
index=j;
}
if(i!=index)
{
temp=a[index];
a[index]=a[i];
a[i]=temp;
}
}
}
}
int main()
{
DataType a[10];
int i;
for(i=0;i<10;i++)
cin>>a[i];
//true表示升序排列,false表示降序排列
SelectSort(a,10,false);
for(i=0;i<10;i++)
cout<<a[i]<<' ';
cout<<endl;
return 0;
}
插入排序算法:
#include<iostream>
using namespace std;
typedef int DataType;
void InsertSort(DataType a[],int n,bool flag)
{
int i,j,k=-1;
DataType temp;
if(flag)
{
for(i=1;i<n;i++)
{
temp=a[i];
j=i-1;
while(j>-1 && temp<a[j])
{
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
}
else
{
for(i=1;i<n;i++)
{
temp=a[i];
j=i-1;
while(j>-1 && temp>a[j])
{
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
}
}
int main()
{
DataType a[10]={0,4,5,6,-8,9,11,23,30,-3};
//true表示升序排列,false表示降序排列
InsertSort(a,10,true);
for(int i=0;i<10;i++)
cout<<a[i]<<' ';
cout<<endl;
return 0;
}
快速排序算法:
#include<stdio.h>
void QuickSort(int *a,int low,int high);
int FindPos(int *a,int low,int high);
void main()
{
int a[6]={-2,1,-78,5,4,-3};
int i;
QuickSort(a,0,5);
for(i=0;i<5;i++)
printf("%d ",a[i]);
printf("\n");
}
void QuickSort(int *a,int low,int high)
{
int pos;
if(low<high)
{
pos=FindPos(a,low,high);
QuickSort(a,low,pos-1);
QuickSort(a,pos+1,high);
}
}
int FindPos(int *a,int low,int high)
{
int val=a[low];
while(low<high)
{
while(low<high && a[high]>=val)
--high;
a[low]=a[high];
while(low<high && a[low]<=val)
++low;
a[high]=a[low];
}
a[low]=val;
return low;
}
哈希排序算法:注意这里只能对0—32767范围内的整数排序
#include<iostream>
using namespace std;
void HashSort(int a[],int n,bool flag)
{
int i,j,k=0,Hash[32767]={0};
for(i=0;i<n;i++)
Hash[a[i]]++;
if(flag)
{
for(i=0;i<=32767-1;i++)
{
if(Hash[i]!=0)
{
for(j=1;j<=Hash[i];j++)
a[k++]=i;
}
}
}
else
{
for(i=32767-1;i>=0;i--)
{
if(Hash[i]!=0)
{
for(j=1;j<=Hash[i];j++)
a[k++]=i;
}
}
}
}
int main()
{
int a[10]={4,2,1,6,7,8,2,3,1,9};
HashSort(a,10,false);
for(int i=0;i<10;i++)
cout<<a[i]<<' ';
cout<<endl;
return 0;
}
以上几个算法是在晚上写的,如有错误或不足之处请留言,我会及时更正!