zoukankan      html  css  js  c++  java
  • C# 数据结构与算法系列(六) 排序之直接插入排序法

    直接插入排序的基本思路是:顺序地将待排序的记录按其关键码的大小插入到已排序的记录子序列的适当位置。设待排序的顺序表List中有n个记录,初始时子序列中只有一个记录List[0],第一次排序时,把List[1]与List[0]比较大小,若List[0]<=List[1],说明不需要排序,否则把位置改变过来,第二次排序的时候,List[2]与List[1]比较大小,如果List[2]比List[1]小,再和List[0]比,然后插入到合适的位置。
    算法如下:
    首先定认一个需要排序的数组:
    int[] array = new int[6] { 2, 1, 4, 3, 6, 5 };
    下面就是排序的代码:
    一、DESC方法
     static void descInsertSort(int[] array)
            {
                
    for (int i = 1; i < array.Length; i++)
                {
                    
    if (array[i] > array[i - 1])
                    {
                        
    int tmp = array[i]; 
                        
    int j = 0;
                        
    for (j = i - 1; j >= 0 && tmp >array[j]; --j)
                        {
                            array[j 
    + 1= array[j];
                        }
                        array[j 
    + 1= tmp;
                    }
                }
            }

    二:ASC方法
            static void ascInsertSort(int[] array)
            {
                
    for (int i = 1; i < array.Length; i++)
                {
                    
    if (array[i] < array[i - 1])
                    {
                        
    int tmp = array[i];
                        
    int j = 0;
                        
    for (j = i - 1; j >= 0 && tmp < array[j]; --j) 
                        {
                            array[j 
    + 1= array[j];
                        }
                        array[j 
    + 1= tmp;
                    }
                }
            }

    下面是测试的代码:
            static void Main(string[] args)
            {
                
    try
                {
                    
    int[] array = new int[6] { 214365 };
                    Console.WriteLine(
    "----DESC----");
                    descInsertSort(array);
                    
    for (int i = 0; i < array.Length; i++)
                    {
                        Console.WriteLine(array[i]);
                    }
                    Console.WriteLine(
    "----ASC----");
                    ascInsertSort(array);
                    
    for (int i = 0; i < array.Length; i++)
                    {
                        Console.WriteLine(array[i]);
                    }
                    Console.ReadLine();
                }
                
    catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.ReadLine();
                }            
            }

    结果如下图


  • 相关阅读:
    iOS应用程序的登录界面
    访问Mac下virtualbox中的win8.1虚拟机
    JASIG-CAS学习笔记——初探CAS
    跨域读取Cookies(续)
    跨域读取Cookies
    错误——无法找到com/* /* /**.xml
    设计模式学习之——简单工厂、工厂方法、抽象工厂方法
    spring+ibatis+dwr+ext项目整合
    SenchaTouch学习——form表单
    FLEX自定义事件
  • 原文地址:https://www.cnblogs.com/whtydn/p/1540397.html
Copyright © 2011-2022 走看看