排序算法-SelectSort-选择排序

1. 选择排序算法介绍

每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。选择排序是不稳定的排序方法。时间负责度为O(n^2)。

2. 算法实现

2.1 选择排序<由高到低>

//type * pArray: 待排序数组指针
//int len:数组的长度
//typename type:模板库
template <typename type>
void SelectSortHigh2Low(type * pArray, int len);

template <typename type>
void SelectSortHigh2Low(type * pArray, int len)
{
    int i, j;
    int temp;
    for (i=0; i<len-1; i++)
    {
        temp = i;
        for (j=i+1; j<len; j++)
        {
            if (pArray[temp]<pArray[j])
                temp = j;
        }
        if (temp!=i)
            Swap(&pArray[i], &pArray[temp]);
    }
}

2.2 选择排序<由低到高>

//type * pArray: 待排序数组指针
//int len:数组的长度
//typename type:模板库
template <typename type>
void SelectSortlow2High(type * pArray, int len);
template <typename type>
void SelectSortlow2High(type * pArray, int len)
{
    int i, j;
    int temp;
    for (i=0; i<len-1; i++)
    {
        temp = i;
        for (j=i+1; j<len; j++)
        {
            if (pArray[temp]>pArray[j])
                temp = j;
        }
        if (temp!=i)
            Swap(&pArray[i], &pArray[temp]);
    }
}

2.3 交换数值

template <typename type>
void Swap(type * lhs, type * rhs)
{
    type temp = *lhs;
    *lhs = *rhs;
    *rhs = temp;
}

3. 示例

在主函数中输入10个等长的字符串(每个字符串最多10个字符),对他们进行由大到小的排序,然后再主函数进行输出结果。
输入
10个等长的字符串,用空格分隔。
输出
输出排序后的字符串

样例:
输入: she its can ibm bbc NBA nhk BOY jxf eat
输出: BOY NBA bbc can eat ibm its jxf nhk she

//数组定义:
void arrary[3][10];//连续型的数组定义

void SelectSortLow2High(char pArray[][10], int len)
{
    int i, j;
    int temp;
    for (i=0; i<len-1; i++)
    {
        temp = i;
        for (j=i+1; j<len; j++)
        {
            if ( memcmp(pArray[temp], pArray[j], strlen(pArray[j])) > 0 )
                temp = j;
        }
        if (temp!=i)
            Swap(pArray[i], pArray[temp]);
    }
}

void Swap(char * lhs, char * rhs)
{
    char temp[10] = {'\0'};
    memcpy(temp, lhs, strlen(lhs));
    memcpy(lhs, rhs, strlen(rhs));
    memcpy(rhs, temp, strlen(temp));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值