几种常见排序算法实现

*排序*/
#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lambp314

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值