插入排序算法

package com.liu.sort_test;


/**
 * 插入排序 升序
 * 
 * @author liu
 * 
 */
public class InsertSort {
static int arr[] = new int[] { 1, 3, 2, 5, 4, 7, 8, 0, 9 };


public static void main(String[] args) {
// 要循環的次數
for (int i = 1; i < arr.length; i++) {
int j = i - 1;// 基數的下標
int temp = arr[i];// 要插入的數據
// 即將插入的數據和之前的數據進行比較
while (j >= 0 && temp < arr[j]) {
// 直到找到不比基數小的位置
arr[j + 1] = arr[j];
j--;
}
// 在該位置插入
arr[j + 1] = temp;
}
//打印出來
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
發佈了26 篇原創文章 · 獲贊 8 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章