码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 排序

时间:2015-11-17 23:08:36      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

#include<iostream>
using namespace std;
#include<ctime>
#include<cstdlib>
typedef int KeyType;
typedef char * InfoType;
typedef struct
{
    KeyType key;
    InfoType otherinfo;
}ElemType;
typedef struct
{
    ElemType *R;
    int length;
}SqList;

int CmpNum0;
int CmpNum1;
int CmpNum2;
int CmpNum3;

void CreateList(SqList &L,int n)
{
    int i;
    L.R=new ElemType[n+1];
    srand(time(0));
    for(i=1;i<=n;i++)
    {
        L.R[i].key=rand()%100;    
    }
    L.length=n;
}

void ListTraverse(SqList L)
{
    int i;
    for(i=1;i<=L.length;i++)
        cout<<L.R[i].key<<‘\t‘;
    cout<<endl;
}

void BubbleSort(SqList &L)
{
    int m,flag,i;
    m=L.length-1;flag=1;
    while(m>0&&flag)
    {
        flag=0;
        for(i=1;i<=m;i++)
        {
            CmpNum0++;
            if(L.R[i].key>L.R[i+1].key)
            {
                flag=1;
                L.R[0]=L.R[i+1];
                L.R[i+1]=L.R[i];
                L.R[i]=L.R[0];
            }
        }
        m--;
    }
}

 

void InsertSort(SqList &L)
{    //对顺序表L做直接插入排序
        int i,j;
        for(i=2;i<=L.length;++i)
        {
            CmpNum1++;
            if(L.R[i-1].key>L.R[i].key)       //">"需将R[i]插入有序子表
            
            {
                L.R[0]=L.R[i];        //将待插入的记录暂存到监视哨中
                L.R[i]=L.R[i-1];      //R[i-1]后移
                for(j=i-2;L.R[0].key<L.R[j].key;--j)   //从后面向前寻找插入位置
                    L.R[j+1]=L.R[j];      //记录逐个后移,直到找到插入位置
                L.R[j+1]=L.R[0];      //将R[0]即原R[i],插入到正确位置
            }
        }
}

 

void BInsertSort(SqList &L)
{      //对顺序表L做折半插入排序
        int i,j,low,high,m;
        for(i=2;i<=L.length;++i)
        {
            CmpNum2++;
            L.R[0]=L.R[i];          //将待插入的记录暂存到监视哨中
            low=1;high=i-1;        //置查找区间初值
            while(low<=high)       //在R[low...high]中折半查找插入的位置
            {
                m=(low+high)/2;     //折半
                if(L.R[m].key>L.R[0].key) high=m-1;   //插入点在前一子表
                else low=m+1;    //插入点在后一子表
                
            }
            for(j=i-1;j>=high+1;--j)    
                L.R[j+1]=L.R[j];          //记录后移 
            L.R[high+1]=L.R[0];        //将R[0]即原R[i],插入到正确位置
        }
}


int main()
{
    SqList L;
    CreateList(L,8);
    cout<<"测试数据:"<<endl;
    ListTraverse(L);
    BubbleSort(L);
    cout<<"排序后:"<<endl;
    ListTraverse(L);
    cout<<"BubbleSort排序方法中数据的比较次数为:"<<CmpNum0<<endl;
  InsertSort(L);
    cout<<"排序后:"<<endl;
    ListTraverse(L);
    cout<<"InsertSort排序方法中数据的比较次数为:"<<CmpNum1<<endl;
    BInsertSort(L);
    cout<<"排序后:"<<endl;
    ListTraverse(L);
    cout<<"BInsertSort排序方法中数据的比较次数为:"<<CmpNum2<<endl;
    return 0;
}

C++ 排序

标签:

原文地址:http://www.cnblogs.com/YY-Xcode/p/4972973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!