我的理解是从数组第二个元素开始依次和前面的元素比较,小于前面则交换位置,直到插入的位置正确为止。
代码实现如下:
using System; namespace 插入排序 { class Program { static void Main(string[] args) { int[] iarray = new int[100]; Random rd=new Random(); //为数组随机填充100个数 for (int i = 0; i < iarray.Length; i++) { iarray[i] = rd.Next(0, 10000); } for (int i = 1; i < iarray.Length; i++) { for (int j = i; j - 1 >= 0; j--) { if (iarray[j] < iarray[j - 1]) { int tmp = iarray[j]; iarray[j] = iarray[j - 1]; iarray[j - 1] = tmp; } else { break; } } } foreach (int j in iarray) { Console.Write(j+" "); } } } }
而网上的插入排序一般是这样的:
public class SortHelper { public static void InsertSort<T>(T[] array) where T : IComparable { int length = array.Length; for (int i = 1; i < length; i++) { T temp = array[i]; if (temp.CompareTo(array[i - 1])<0) { for (int j = 0; j < i; j++) { if (temp.CompareTo(array[j])<0) { temp = array[j]; array[j] = array[i]; array[i] = temp; } } } } } }