算法描述:對于給定的一個數(shù)組,初始時假設第一個記錄自成一個有序序列,其余記錄為無序序列。接著從第二個記錄開始,按照記錄的大小依次將當前處理的記錄插入到其之前的有序序列中,直至最后一個記錄插入到有序序列中為止。
示例1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
public class Insert { public static void main(String[] args) { int a[] = { 9 , 3 , 28 , 6 , 34 , 7 , 10 , 27 , 1 , 5 , 8 }; show(a); for ( int i= 1 ;i insertOne(a, i); } show(a); } static void show( int a[]){ for ( int i= 0 ;i System.out.print(a[i]+ " " ); } System.out.println(); } //把第k個元素融入到前面有序隊列 static void insertOne( int a[], int k){ for ( int i= 0 ;i<=k;i++){ if (a[i]>=a[k]){ int temp = a[k]; //移動之前先把a[k]放到一個中間變量處 //從k位置前面的數(shù)依次往后移動,直到i位置 for ( int j=k- 1 ;j>=i;j--){ a[j+ 1 ] = a[j]; } a[i] = temp; //把中間變量中的值給a[i],移動之后i處的值為空。 } } } } |
示例2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package sorting; /** * 插入排序 * 平均O(n^2),最好O(n),最壞O(n^2);空間復雜度O(1);穩(wěn)定;簡單 * @author zeng * */ public class InsertionSort { public static void insertionSort( int [] a) { int tmp; for ( int i = 1 ; i < a.length; i++) { for ( int j = i; j > 0 ; j--) { if (a[j] < a[j - 1 ]) { tmp = a[j - 1 ]; a[j - 1 ] = a[j]; a[j] = tmp; } } } } public static void main(String[] args) { int [] a = { 49 , 38 , 65 , 97 , 76 , 13 , 27 , 50 }; insertionSort(a); for ( int i : a) System.out.print(i + " " ); } } |
總結(jié)
以上就是本文關(guān)于Java編程實現(xiàn)直接插入排序代碼示例的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:https://www.2cto.com/kf/201712/705547.html