This time I will write the code for insertion sort.
InsetionSort.java
//It feels like sorting cards in your hand.
public class InsertionSort {
public static void sort(int[] array) {
for(int i=1;i<array.length;i++) {
int j=i;
while(j>=1 && array[j-1]>array[j]) {
int temp = array[j];
array[j] = array[j-1];
array[j-1] = temp;
j--;
}
}
}
public static void main(String args[]) {
int[] array = {3,2,4,5,1};
sort(array);
for(int i=0;i<array.length;i++) {
System.out.print(array[i]);
}
}
}
Next time I'll try shellsort.
Recommended Posts