您的位置:首页 > 其它

几种常见排序算法实现

2009-02-24 14:53 411 查看
*排序*/
#include <iostream.h>
#include <stdlib.h>

typedef int keytype;
typedef struct
{
keytype key;
} DataType;

//插入排序
void InsertSort(DataType a[],int n)
{
int i,j,k;
DataType temp;
for(i = 0; i<n-1;i++)
{
temp = a;
j = i;
while(j > -1 && temp.key < a[j].key)
{
a[j+1] = a[j];
j--;
}
a[j+1] = temp;
cout << "第"<<i+1<<"次排序后:";
for(k=0;k<n;k++)
{
cout << a[k].key << " ";
}
cout << endl;
}
}
//希尔排序
void ShellSort(DataType a[],int n,int d[], int num)
{
int i ,j,m,span,k,l;
DataType temp;
for(m = 0;m <num;m++)
{
span = d[m];
for(k = 0;k <span;k++)
{
for(i = k;i < n-span;i=i+span)
{
temp = a;
j = i;
while(j > -1 && temp.key < a[j].key)
{
a[j + span] = a[j];
j = j-span;
}
a[j+span] = temp;
}
}
cout << "第"<<m+1<<"次排序后:";
for(l=0;l<n;l++)
{
cout << a[l].key << " ";
}
cout << endl;
}
}
//冒泡排序
void bubblesort(DataType a[],int n)
{
int i,j,flag = 1,k;
DataType temp;
for(i = 1;i < n && flag == 1;i++)
{
flag = 0;
for(j = 0;j<n-1;j++)
{
if(a[j].key > a[j+1].key)
{
flag = 1;
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
cout << "第"<<i+1<<"次排序后:";
for(k=0;k<n;k++)
{
cout << a[k].key << " ";
}
cout << endl;
}
}
//快速排序
void quicksort(DataType a[],int low,int hight)
{
int i = low,j = hight,k;
DataType temp = a[low];
while(i < j)
{
//在数组右边扫描
while(i < j && temp.key <= a[j].key) j--;
if(i < j)
{
a= a[j];
i++;
}
//在数组左边扫描
while(i < j && a.key <temp.key) i++;
if(i < j)
{
a[j] = a;
j--;
}
}
a = temp;
if(low < i) quicksort(a,low,i-1);//左边递归
if(i < hight) quicksort(a,j+1,hight);//右边递归
cout << "第"<<i<<"次排序后:";
for(k=0;k<8;k++)
{
cout << a[k].key << " ";
}
cout << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: