直接插入排序


4 1
using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 直接插入排序 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 int n; 14 n = int.Parse(Console.ReadLine()); 15 int[] SeqList = new int[n]; 16 for(int i=0;i<n;i++) 17 { 18 SeqList[i]= Convert.ToInt32(Console.ReadLine()); 19 } 20 InsertSort(SeqList); 21 foreach(var str in SeqList) 22 { 23 Console.Write(str + " "); 24 } 25 Console.ReadKey(); 26 } 27 static void InsertSort(int[]s) 28 { 29 for(int i=1;i<s.Length;i++) 30 { 31 if(s[i]<s[i-1]) //4 3 5 2 6 32 { 33 int temp = s[i];//temp的作用有两个:1.为了接下来的数值交换 2.在第二层的循环中与前面的数比较大小 34 int j = 0; 35 for(j=i-1;j>=0&&temp<s[j];j--)//temp的第二个作用 36 { 37 s[j + 1] = s[j]; 38 } 39 s[j + 1] = temp; //temp的第一个作用 40 } 41 } 42 } 43 } 44 }

假设一个数组为:3 4 2 1 5

第一次 4与3比较,即s[i]与s[i-1]比较,如果大于,则跳出

第二次2与4比较,2小于4,将2的值赋给临时变量temp,之后在子循环里循环判断2与其之前的所有值的大小关系,如果2小,则将大的值赋给2所在的数组位置;子循环结束,temp赋值给与2最后比较完的数组位置

     即2赋给seqlist【0】,当前顺序为:2 3 4

如此往复

关于时间复杂度

  最好的情况为顺序有序,这时外层循环的比较次数为n-1,if条件的比较次数也为n-1,所以比较次数为2(n-1),时间复杂度为O(n)

  最坏情况则为逆序有序,时间复杂度为O(n^2)

另外,本来函数的参数我设的是ref,删去ref后才发现也可以双向传递,因为数组是引用类型。

posted @ 2018-09-15 08:10  本咒  阅读(237)  评论(1编辑  收藏  举报