zoukankan      html  css  js  c++  java
  • 选择排序优化

    选择排序
       选择排序是一种直观的排序算法.它的原理是每一次从待排序中选出最小或最大的一个元素,
    存放在序列的起始位置,直到全部待排序的数据元素排完.选择排序是不稳定的排序方法
    (比如:[5,5,2],在第一次就将第一个5与3交换了,导致第一个5挪到第二个5后面)。
    实现:
    void SelectSort(type a[],int len)
    {
                type temp;
                int nIndex = 0;
                int i,j;
                for(i=0;i<len-1;i++)
                {
                    nIndex=i;
                    for(j=i+1;j<len;j++)
                    {
                        if(a[j]<a[nIndex])
                        {
                            nIndex = j;
                        }
                    }
                    if(nIndex != i)
                    {
                        temp = a[i];
                        a[i]= a[nIndex];
                        a[nIndex]=temp;
                    }
                }
    }
    二元选择排序
        简单的选择排序,每趟循环只能确定一个元素排序后的定位,我们可以考虑每趟循环确定
    两个元素(当前趟的最大和最小记录)的位置,从而减少排序所需的循环次数。改进后对n个
    数据进行排序,最多只需进行【n/2】趟排序即可
    代码实现:
        void SelectSort(int r[],int n)
        {
            int i,j,min,max,tmp;
            for(i=0;i<=n/2;i++)
            {
                min = i;
                max = i;
                for(j = i+1; j<=n-i; j++)
                {
                    if(r[j] > r[max])
                    {
                        max = j;
                        continue;
                    }
                    if(r[j] < r[min])
                    {
                        min = j;
                    }
                }
                tmp = r[i];
                r[i] = r[min];
                r[min] = tmp;
                tmp = r[n-i];
                r[n-i] = r[max];
                r[max] = tmp;
            }
        }

    The future's not set,there is no fate but what we make for ourselves.
  • 相关阅读:
    IBM:linuxdeveloperweb
    xen虚拟化及工作原理
    (转) mysql 8小时空闲后连接超时的问题
    (转) 分布式缓存系统Memcached简介与实践
    ubuntu server 使用memcachetop监测memcache集群
    心安
    (转)Mysql导出表结构及表数据 mysqldump用法
    一个老工程师的心理话
    memcache设置set过期时间
    (转)memcached配置及命令
  • 原文地址:https://www.cnblogs.com/wang1994/p/9115447.html
Copyright © 2011-2022 走看看