现在的位置: 首页 > 综合 > 正文

几个排序

2013年04月20日 ⁄ 综合 ⁄ 共 1622字 ⁄ 字号 评论关闭
 //////////////////////////////////////////////////////////////////////////
//                       直接插入排序
//      顺序的把待排序的数据元素按照关键字插入已经排序好的子集合中,
//      但子集合与原集合个数相同时结束比较。
//////////////////////////////////////////////////////////////////////////
void InsertSort(int a[],int n)
{
    int i,j;
    int temp;
    bool flag = true;
    for (i=1;i<n;i++)
    {
        temp = a[i];
        j=i-1;
        while (temp < a[j] && j>-1)
        {
            a[j+1] = a[j];
            j--;
        }
        a[j+1] = temp;
    }
    cout<<"直接插入排序:"<<endl;
    for (i=0;i<n;i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
}
//////////////////////////////////////////////////////////////////////////
//  直接选择排序
//  从待排序的数据元素中选取关键字最小的那个数据元素插入到原数据元素的首位
//  依次类推。
//////////////////////////////////////////////////////////////////////////
void SelectSort(int a[],int n)
{
    int i,j,small;
    int temp;
    for (i=0;i<n;i++)
    {
        small = i;
        temp =a[i];
        for (j=i+1;j<n;j++)
        {
            if (temp > a[j])
            {
                temp = a[j];
                small = j;
            }
        }
        a[small] = a[i];
        a[i] =temp;
    }
    cout<<"直接选择排序:"<<endl;
    for (i=0;i<n;i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
}
//////////////////////////////////////////////////////////////////////////
//                 冒泡排序
//   相邻的元素之间依次进行比较,每次总是将最大的放到最后后面;
//////////////////////////////////////////////////////////////////////////
void BubbleSort(int a[],int n)
{
    int i,j;
    int temp;
    for (i=1;i<n;i++)
    {
        for (j=0;j<n-i;j++)
        {
            if (a[j] > a[j+1])
            {
                temp = a[j];
                a[j] = a[j+1];
                a[j+1] = temp;
            }
        }
    }
    cout<<"冒泡排序:"<<endl;
    for (i=0;i<n;i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
}

抱歉!评论已关闭.