直接插入排序:把一个无序的表进行排列成有序顺序的表。每次从无序表中选取第一个元素,插入到有序表中,使得有序表仍然有序。
源码:
package insertsort;
public class InsertSort {
public static void insertSort(int[] array) {
for (int i = 1; i < array.length; i++) {
int j = i;
while (j>=1 && array[j]<array[j - 1]) {
int temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
j--;
}
}
}
public static void main(String[] args) {
int[] testArray = {23, 25, 12, 42, 35};
insertSort(testArray);
System.out.println("The result is:");
for (Integer item : testArray) {
System.out.print(item);
System.out.print(' ');
}
}
}