using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _005_直接插入 { class Program { static void Main(string[] args) { int[] data = new int[] { 42, 20, 75, 62, 24, 18, 8, 14, 35,57,18}; InsertSort_1(data); for (int i = 0; i < data.Length; i++) { Console.Write(data[i]+" "); } } /// <summary> /// 实现方法1 /// </summary> /// <param name="dataArray"></param> public static void InsertSort(int[] dataArray) { int iValue; for (int i = 1; i < dataArray.Length; i++) { bool isInsert = false; //拿到i位置得元素 跟前面所有得元素比较 iValue =dataArray[i]; //如果发现比i大得,就让它向后移动 for (int j =i-1; j >=0 ; j--) { if (dataArray[j] > iValue) { dataArray[j+1] = dataArray[j]; } else { //发现一个比i小得值就不移动 dataArray[j+1] = iValue; isInsert = true; break; } } if (isInsert == false) { dataArray[0] = iValue; } } } /// <summary> /// 实现方法2 /// </summary> /// <param name="dataArray"></param> public static void InsertSort_1(int[] dataArray) { int iValue; for (int i = 1; i < dataArray.Length; i++) { //拿到i位置得元素 跟前面所有得元素比较 iValue = dataArray[i]; int j = i - 1; //如果发现比i大得,就让它向后移动 while (j>=0 && dataArray[j]>iValue) { dataArray[j + 1] = dataArray[j]; j--; } //发现一个比i小得值就不移动 dataArray[j + 1] = iValue; } } } }