1. 程式人生 > >排序算法-直接插入排序

排序算法-直接插入排序

log false clas ins class gen stat lin nbsp

技術分享圖片

技術分享圖片

技術分享圖片

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; } } } }

排序算法-直接插入排序