插入排序
思想:用后一项元素与当前项进行比较,如果后一项<当前项,交换位置,保证每一次遍历最小元素归位
插入排序:
public static void insertSort(int[] array){
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j > 0 ; j--) {
if(array[j] < array[j - 1]){
Swap.swap(array,j,j-1);
}
}
}
}
改进:
public static void insertSort2(int[] array){
for (int i = 1; i < array.length; i++) {
int j = 0;
int current = array[i];
for (j = i - 1; j >= 0 && array[j] > current ; j--) {
array[j + 1] = array[j];
}
array[j + 1] = current;
}
}
示例:
public class InsertSort {
public static void main(String[] args) {
insertSort2(Swap.array);
Swap.print(Swap.array);
}
public static void insertSort(int[] array){
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j > 0 ; j--) {
if(array[j] < array[j - 1]){
Swap.swap(array,j,j-1);
}
}
}
}
public static void insertSort2(int[] array){
for (int i = 1; i < array.length; i++) {
int j = 0;
int current = array[i];
for (j = i - 1; j >= 0 && array[j] > current ; j--) {
array[j + 1] = array[j];
}
array[j + 1] = current;
}
}
}
工具:
public class Swap {
static int[] array = {8,2,5,9,3,10,22,1,87};
public static void swap(int[] array,int x,int y){
int temp = array[x];
array[x] = array[y];
array[y] = temp;
}
public static void print(int[] array){
for (int i = 0; i < array.length; i++) {
System.out.print(" " + array[i]);
}
}
}
|