插入排序C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 插入排序
{
    class Program
    {
        static int[] data = new int[6];
        static int size = 6;

        static void Main(string[] args)
        {
            InputArr();
            Console.WriteLine("您输入的数组是");
            Showdata();
            Insert();
        }
        static void InputArr()
        {
            for (int i = 0; i < size; i++)
            {
                try
                {
                    Console.Write("请输入第"+(i+1)+"个元素:");
                    data[i] = int.Parse(Console.ReadLine());
                }
                catch (Exception e)
                {
                }
            }
        }
        static void Showdata()
        {
            for (int i = 0; i < size; i++)
            {
                Console.Write(data[i]+" " );
            }
            Console.WriteLine();
        }
        static void Insert()
        {
            int i;
            //i为扫描次数
            int j;
            //以j来定位比较的元素
            int tmp;
            //tmp用来暂存数据
            for ( i = 1; i < size; i++)
            {
                tmp = data[i];
                j = i - 1;
                while(j>=0 && tmp < data[j])
                {
                    //如果第二个元素小于第一个元素
                    data[j + 1] = data[j];
                    j--;
                }
                data[j + 1] = tmp;
                //最小的元素放在第一个位置
                Console.Write("第"+i+"次扫描的排序结果为:");
                Showdata();
            }
        }
    }
}

在这里插入图片描述
插入排序法的分析:
(1) 最坏情况和平均情况需要比较(n-1)+(n-2)+(n-3)+…+3+2+1=n(n-1)/2 次,
时间复杂度为O(n²);最好情况的时间复杂度为O(n).
(2)插入排序是稳定排序法。
(3)只需要一个额外空间,所以空间复杂度为最佳。
(4) 此排序法适用于大部分数据已经排序或已排序数据库新增数据后进行排序的情况。
(5)因为插入排序法会造成数据的大量搬移,所以建议在链表上使用

发布了13 篇原创文章 · 获赞 0 · 访问量 665

猜你喜欢

转载自blog.csdn.net/Somewater_/article/details/103417790