直接插入排序:时间复杂度为0(n^2)
第i个元素之前的元素已经排序好了,要把数组中的第i个元素排入已经排好的元素中,i要与i-1,i-2.......等元素比较,i大于他们就终止排序,i小于i-1或其他的就把i与他们交换,实现排序的功能
using System; using System.Collections.Generic; using System.Diagnostics;//StopWatch类的命名空间 using System.Linq; using System.Text; using System.Threading.Tasks; namespace 直接插入排序 { class Program { static void Main(string[] args) { int[] array = new int[] { 42, 20, 99, 12, 44, 4, 66, 88, 24, 93 ,1,22};//需要排序的数组 Stopwatch watch = new Stopwatch();//创建StopWatch类的对象 watch.Start();//调用类中的start函数开始计时 Sort(array);//调用直接插入排序函数对数组进行排序 watch.Stop();//调用StopWatch类中的stop函数,终止计时 Console.WriteLine(watch.Elapsed);//输出直接插入排序的用时 foreach (var item in array)//输出已近排序好的数组 { Console.WriteLine(item); } Console.ReadKey(); } /// <summary> /// 直接插入排序 /// </summary> /// <param name="array"></param> public static void Sort(int[] array) { for (int i = 1; i < array.Length; i++)//对数组从第二个数开始排序 { int temp = array[i]; for(int j=i-1;j>=0;j--) { if(temp<array[j]) { array[j + 1] = array[j]; array[j] = temp; } else { break;//已近排序好本次数组了,终止排序 } } } } } }