/**
* INSERTION-SORT(A)
* for j = 2 to A.length
* key = A[j]
* //Insert A[j] into the sorted sequence A[1..j-1].
* i = j - 1
* while i>0 and A[i] > key
* A[i+1] = A[i]
* i = i-1
* A[i+1] = key
*
* */
public class InsertSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> raw = new ArrayList<Integer>();
raw.add(5);
raw.add(2);
raw.add(4);
raw.add(6);
raw.add(1);
raw.add(3);
int rawLength = raw.size();
for(int i = 1; i < rawLength; i++){
int current = raw.get(i);
int j = i-1;
while(j>=0 && raw.get(j)>current){
raw.set(j+1, raw.get(j));
j--;
}
raw.set(j+1, current);
}
for(int r : raw){
System.out.println(r);
}
}
}
插入排序(INSERTION-SORT)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.