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();
                }            
            }

    结果如下图


  • 相关阅读:
    运营设计方法论
    使用 typescript ,提升 vue 项目的开发体验(2)
    PAT 1078. 字符串压缩与解压
    PAT 1077. 互评成绩计算
    PAT 1076. Wifi密码
    PAT 1075. 链表元素分类
    PAT 1074. 宇宙无敌加法器
    PAT 1073. 多选题常见计分法
    PAT 1072. 开学寄语
    PAT 1071. 小赌怡情
  • 原文地址:https://www.cnblogs.com/whtydn/p/1540397.html
Copyright © 2011-2022 走看看