嘉盟

导航

插入排序-JAVA实现

 1 import java.util.Random;
 2 
 3 public class Sort1 {
 4 
 5 //插入 and shell排序
 6 
 7 public static void main(String[] args) {
 8 int a[]= new int[10];
 9 
10 for(int i=0;i<10;i++){
11 Random rand= new Random();
12 a[i]=rand.nextInt(100);
13 }
14 System.out.println("待排序数列");
15 for(int i=0;i<10;i++)
16 System.out.print(a[i]+" ");
17 System.out.println();
18 insertSort(a);
19 
20 
21 }
22 
23 //插入排序 从小到大
24 public static void insertSort(int a[]){
25 int temp;
26 for(int i=1;i<a.length;i++){
27 temp=a[i];
28 for(int j=i-1;j>=0;j--){
29 if(temp<a[j]){
30 a[j+1]=a[j];
31 a[j]=temp;
32 }
33 }
34 }
35 System.out.println("插入排序的结果为:");
36 for(int i=0;i<10;i++)
37 System.out.print(a[i]+" ");
38 
39 }
40 }

 

 

数据结构一年前已经学过了 现在正好复习,记录下自己的复习过程。

 

插入排序 没什么说的 O(n2)

 

 

 

 

 

结果

 

 

posted on 2018-03-07 16:36  嘉盟  阅读(100)  评论(0)    收藏  举报