思路:
将数组的0到0位置弄有序,再将0到1位置弄有序,再将0到2位置弄有序,最后将0到n-1位置弄有序,这个数组也就有序了。
我们假设有一个数组,2, 3, 4, 1, 3。0到0上的位置就只有一个数字2,有序,不用做改变。
0到1有序,0到2有序。好,现在到0到3了。
现在是0到4了。
代码:
import java.util.Scanner; public class InsertSort { //插入排序算法核心 public static void insert(int a[]) { if(a == null || a.length < 2) { return; } for(int i = 1; i < a.length; i++) { for(int j = i - 1; j >= 0 && a[j] > a[j + 1]; j--) { swap(a, j, j + 1); } } } //将数组中的两个数交换 public static void swap(int a[], int i, int j) { int temp; temp = a[i]; a[i] = a[j]; a[j] = temp; } public static void main(String args[]) { //输入数组中有几个数 System.out.print("请输入一个正整数:"); Scanner input = new Scanner(System.in); int n = input.nextInt(); //创建数组 int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = input.nextInt(); } input.close(); //调用插入排序函数 insert(a); //输出排序后的数组 for(int i = 0; i < n; i++) { System.out.println(a[i]); } } }
实验结果图:
文章来源: 详解插入排序算法