排序算法之插入排序代码实现

插入排序,顾名思义,是将符合一定条件的值插入到序列当中,实际上插入排序是十分有序的,原理也十分的简单。

并且,由插入排序更引申出了希尔排序的实现,其实也就是插入排序的优化。

 1 import java.util.Scanner;
 2 public class Insertion_Sort {
 3     public static void main(String[] args) {
 4         int i,j;
 5         Scanner sc = new Scanner(System.in);
 6         int n = sc.nextInt();
 7         int[] a = new int[n];
 8         for( i = 0;i<a.length;i++) {
 9             a[i] = sc.nextInt();
10         }
11         for(i = 0;i<a.length;i++) {
12             int value = a[i];
13             for(j = i-1;j>=0;j--) {
14                 if(a[j]>value) {
15                     a[j+1] = a[j];
16                 }
17  18             }
19             a[j+1] = value;
20             for(int num:a) {
21                 System.out.print(num+" ");
22             }
23             System.out.println();
24         }
25         
26     }
2

 我在每一次循环都给了输出,方便观察是如何进行插入排序的。

猜你喜欢

转载自www.cnblogs.com/whtmomo/p/11995890.html
今日推荐