(直接)插入排序.gif
    在已经排好顺序的元素中找到当前待排元素应该插入的位置并将其插入

    1. import java.util.*;
    2. public class Main {
    3. public static void main(String[] args) {
    4. Scanner sc = new Scanner(System.in);
    5. int n = sc.nextInt();
    6. int[] a = new int[n];
    7. for (int i = 0; i < n; i++)
    8. a[i] = sc.nextInt();
    9. for (int i = 1; i < a.length; i++) {
    10. int key = a[i], j = i;
    11. while (j - 1 >= 0 && a[j - 1] > key) {
    12. a[j] = a[j - 1];
    13. j--;
    14. }
    15. a[j] = key;
    16. }
    17. for (int i = 0; i < n; i++) {
    18. System.out.print(a[i] + " ");
    19. }
    20. }
    21. }