Java數(shù)據(jù)結構及算法實例:插入排序 Insertion Sort
更新時間:2015年06月20日 11:22:34 投稿:junjie
這篇文章主要介紹了Java數(shù)據(jù)結構及算法實例:插入排序 Insertion Sort,本文直接給出實例代碼,代碼中包含詳細注釋,需要的朋友可以參考下
/**
* 選擇排序的思想:
* 每次循環(huán)前,數(shù)組左邊都是部分有序的序列,
* 然后選擇右邊待排元素,將其值保存下來
* 依次和左邊已經排好的元素比較
* 如果小于左邊的元素,就將左邊的元素右移一位
* 直到和最左邊的比較完成,或者待排元素不比左邊元素小
*/
package al;
public class InsertionSort {
public static void main(String[] args) {
InsertionSort insertSort = new InsertionSort();
int[] elements = { 14, 77, 21, 9, 10, 50, 43, 14 };
// sort the array
insertSort.sort(elements);
// print the sorted array
for (int i = 0; i < elements.length; i++) {
System.out.print(elements[i]);
System.out.print(" ");
}
}
/**
* @author
* @param array 待排數(shù)組
*/
public void sort(int[] array) {
// min to save the minimum element for each round
int key; // save current element
for(int i=0; i<array.length; i++) {
int j = i; // current position
key = array[j];
// compare current element
while(j > 0 && array[j-1] > key) {
array[j] = array[j-1]; //shift it
j--;
}
array[j] = key;
}
}
}
相關文章
SpringMVC中Invalid bound statement (not f
本文主要介紹了SpringMVC中Invalid bound statement (not found)常見報錯問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05
基于Java并發(fā)容器ConcurrentHashMap#put方法解析
下面小編就為大家?guī)硪黄贘ava并發(fā)容器ConcurrentHashMap#put方法解析。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06

