一天一个小算法的学习之插入排序

  把集合划分成有序区域和无序区域,初始时,把第一个元素默认化为有序区域,在每次排序过程中,将无序序列的第一个元素插入到有序序列的适当位置..

  代码:

using System;

namespace SortPra
{
    public class InsertSort
    {
        public InsertSort ()
        {
            
        }

        public static int[] InsertWithSort (int[] arr)
        {
            InsertSortTo (arr);
            for (int i = 0; i < arr.Length; i++) {
                Console.WriteLine ("插入排序:" + arr [i]);
            }
            return arr;
        }

        static void InsertSortTo (int[] arr)
        {
            int i, j, k;
            for (i = 1; i < arr.Length; i++) {
                //保存当前数据,当前数据就是即将待插入的数据
                k = arr [i];
                //排列成递增序列
                for (j = i - 1; j >= 0 && arr [j] > k; j--) {
                    arr [j + 1] = arr [j];
                }
                arr [j + 1] = k;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/jbw752746541/p/8709809.html