C++ 简单选择排序

#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;

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 SelectSort(SqList &L)
{
    int i,j,k;
    ElemType temp;
    for(i=1;i<L.length;i++){
       k=i;
       for(j=i+1;j<=L.length;j++)
          if(L.R[j].key<L.R[k].key) k=j;  //k指向此趟排序中关键字最小的记录
        if(k!=i)
        {//交换R[i]与R[k]
            temp=L.R[i];
            L.R[i]=L.R[k];
            L.R[k]=temp;
        }
    }
}

int main()
{
    SqList L;
    CreateList(L,8);
    cout<<"测试数据:"<<endl;
    ListTraverse(L);
    SelectSort(L);
    cout<<"排序后:"<<endl;
    ListTraverse(L);
    return 0;
}

posted @ 2015-11-18 11:20  IT_程序袁  阅读(469)  评论(0编辑  收藏  举报