日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

直接插入排序(内部排序)

發布時間:2025/3/15 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 直接插入排序(内部排序) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1 package com.trfizeng.insertionsort; 2 3 /** 4 * 5 * @author trfizeng 內部排序 插入排序 --- 直接插入排序(Straight Insertion Sort) 6 * 7 */ 8 public class StraightInsertionSort { 9 public static int[] straightInsertionSort(int[] array) { 10 // 對傳來的待排序數組進行合法驗證 11 if (array != null && array.length != 0) { 12 // 用來控制已排序好記錄下標 13 int j = 0; 14 // i = 0 把第一個當作是有序記錄,之后的全部看著無序記錄 15 for (int i = 1; i < array.length; i++) { 16 // 后一個跟有序記錄最后一個比較 17 if (array[i] < array[i - 1]) { 18 // 把比有序記錄最后一個小的數復制一份作為要插到有序記錄的數,因為在賦值的過程會丟失 19 int temp = array[i]; 20 // 覆蓋掉這個作為要插的記錄使之當前有序記錄數 + 1 21 array[i] = array[i - 1]; 22 // 因為在上面已經比較過了和覆蓋過,所有要去除這2個數 23 j = i - 2; 24 // 拿著這個要插的數跟有序記錄一一對比,只要比當前有序記錄最后一個小的就把這個數后挪一位,為了保證插入排序是穩定的,不能是<= 25 while (j >= 0 && temp < array[j]) { 26 // 使記錄后移 27 array[j + 1] = array[j]; 28 // 比較過就除去,有序記錄數 - 1 29 j--; 30 } 31 // 最后把要插的數插到該插的位置 32 array[j + 1] = temp; 33 } 34 } 35 } 36 return array; 37 } 38 } View Code 1 package com.trfizeng.test; 2 3 import com.trfizeng.insertionsort.StraightInsertionSort; 4 5 /** 6 * 測試類 7 * 8 * @author trfizeng 9 * 10 */ 11 public class SortTest { 12 // 待排序數組 13 static int[] array = new int[] { 6, 1, 4, 10, 11, 8, 7, 1 }; 14 15 /** 16 * 直接插入排序法測試 17 */ 18 public static void straightInsertionSortTest() { 19 System.out.print("待排序數組:[ "); 20 for (int i = 0; i < array.length; i++) { 21 System.out.print(array[i] + " "); 22 } 23 System.out.print("] "); 24 25 array = StraightInsertionSort.straightInsertionSort(array); 26 System.out.print("排好序的數組:[ "); 27 for (int i = 0; i < array.length; i++) { 28 System.out.print(array[i] + " "); 29 } 30 System.out.print("]"); 31 } 32 33 public static void main(String[] args) { 34 SortTest.straightInsertionSortTest(); 35 36 } 37 } View Code

?

轉載于:https://www.cnblogs.com/trfizeng/p/4307725.html

總結

以上是生活随笔為你收集整理的直接插入排序(内部排序)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。