算法系列:各位朋友,我们继续C#算法的学习之路。今天同样是一个简单直观的排序算法--插入排序。插入排序的原理是通过构建有序序列,对未排序序列进行扫描,找到相应位置并插入。插入排序,在数据规模较小或者部分数据已经处于有序的情况下,其效率很高。
插入排序的事件复杂度不唯一,平均值为n的平法,其中n是列表的长度。空间复杂度为1。
C#简单例程如下:
- static void Main()
- {
- int[] array = { 3, 5, 1, 4, 6, 2 };
- Console.WriteLine("原始数组:");
- foreach (int item in array)
- {
- Console.Write(item + " ");
- }
- Console.WriteLine();
-
- InsertionSort(array);
-
- Console.WriteLine("排序后的数组:");
- foreach (int item in array)
- {
- Console.Write(item + " ");
- }
- }
-
- static void InsertionSort(int[] array)
- {
- int n = array.Length;
- for (int i = 1; i < n; i++)
- {
- int key = array[i];
- int j = i - 1;
-
- // 将较大的元素向后移动
- while (j >= 0 && array[j] > key)
- {
- array[j + 1] = array[j];
- j--;
- }
-
- // 将key插入到正确的位置
- array[j + 1] = key;
- }
- }