第一种方法:
插入数值替换方式:从后往前替换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| package com.bhy.test_sort;
public class InsertSort { private int[] arr; public InsertSort(int[] arr) { this.arr = arr; }
public void insert(){ int n; int m; for (int i = 1; i < arr.length; i++) { for (int j = 0; j < i; j++) { if(arr[i] < arr[j]) { m = arr[j]; arr[j] = arr[i]; for (int j2 = j ;j2 < i; j2++) { n = arr[j2+1]; arr[j2+1] = m; m = n; } break; } } } }
}
|
插入数值替换方式:从前往后替换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| package com.bhy.test_sort;
public class InsertSort2 { private int[] arr; public InsertSort2(int[] arr) { this.arr = arr; }
public void insert(){ int n; for (int i = 1; i < arr.length; i++) { for (int j = 0; j < i; j++) { if(arr[i] < arr[j]) { n = arr[i]; for (int j2 = i ; j2 > j ; j2--) { arr[j2] = arr[j2-1]; } arr[j] = n; break; } } } } }
|
第二种方法(改进):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| package com.bhy.test_sort;
public class ProInsertSort {
public static void main(String[] args){ int[] x = { 6, 2, 7, 1, 5, 9 }; insertion_sort(x); for (int i = 0; i < x.length; i++) { System.out.print(x[i]+" "); } }
public static void insertion_sort(int[] arr) { for (int i = 1; i < arr.length; i++) { if(arr[i] < arr[i-1]) { int value = arr[i]; int j = i; while(j>0 && arr[j-1]>value ) { arr[j] = arr[j-1]; j--; } arr[j] = value; } } }
}
|
Author:
brbai
Permalink:
https://br-bai.github.io/2018/11/25/直接插入排序的两种方法/
Slogan:
Make excellence a habit.