public class InsertionSort {
public static void main(String[] args){
int[] array = {6,7,3,8,1,2,3,4,5};
new InsertionSort().insertionSort(array);
for(int i=0; i < array.length ; i++)
System.out.println(array[i]);
}
public void insertionSort(int[] array){
for(int j=1; j <= array.length-1; j++){
insert(array, j);
}
}
//insert array[index] into sorted sequence array[0]...array[index-1]
private void insert(int[] array, int indexToInsert){
int key = array[indexToInsert];
int i = indexToInsert - 1;
while(i >=0 && array[i] > key){
array[i+1] = array[i];
i--;
}
array[i + 1] = key;
}
}
Sunday, May 13, 2012
Insertion Sort in Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment