直接插入排序Java代碼
/**
* 直接插入排序
* @author sikaijian
*/
public class DirectInsertSort {
public static void sort(int[] data){
int pCurrent = 1; // 認定第0個數(shù)是有序的,從第1個數(shù)開始插入排序
int n = data.length;
while(pCurrent<n){
int front = pCurrent-1;
int key = data[pCurrent];
// 當前要插入的數(shù)和左邊的有序隊列比較(從右往左比較,比較一次移動一次)
while(front>-1 && key<data[front]){
data[front+1] = data[front];
front--;
}
data[front+1] = key;
pCurrent++;
}
}
/**
* 測試代碼
* @param args
*/
public static void main(String[] args) {
int[] data = new int[] { 49, 23, 65, 13, 38, 96, 12, 33, 88, 123, 22,
11, 9, 55, 111, 0 };
for (int t : data) {
System.out.print(t);
System.out.print(" ");
}
System.out.println();
System.out.println("------------------------------");
DirectInsertSort.sort(data);
for (int t : data) {
System.out.print(t);
System.out.print(" ");
}
}
}
* 直接插入排序
* @author sikaijian
*/
public class DirectInsertSort {
public static void sort(int[] data){
int pCurrent = 1; // 認定第0個數(shù)是有序的,從第1個數(shù)開始插入排序
int n = data.length;
while(pCurrent<n){
int front = pCurrent-1;
int key = data[pCurrent];
// 當前要插入的數(shù)和左邊的有序隊列比較(從右往左比較,比較一次移動一次)
while(front>-1 && key<data[front]){
data[front+1] = data[front];
front--;
}
data[front+1] = key;
pCurrent++;
}
}
/**
* 測試代碼
* @param args
*/
public static void main(String[] args) {
int[] data = new int[] { 49, 23, 65, 13, 38, 96, 12, 33, 88, 123, 22,
11, 9, 55, 111, 0 };
for (int t : data) {
System.out.print(t);
System.out.print(" ");
}
System.out.println();
System.out.println("------------------------------");
DirectInsertSort.sort(data);
for (int t : data) {
System.out.print(t);
System.out.print(" ");
}
}
}
posted on 2012-09-21 14:23 瓢菝的雨夜 閱讀(211) 評論(0) 編輯 收藏 所屬分類: 數(shù)據(jù)結(jié)構(gòu)算法