插入排序--java

 1 package demo;
 2 
 3 
 4 
 5 public class InsertSort {
 6     private int[] array;
 7     private int length;
 8 
 9     public InsertSort(int[] array){
10         this.array = array;
11         this.length = array.length;
12     }
13 
14     public void display(){
15         for(int a: array){
16             System.out.print(a+" ");
17         }
18         System.out.println();
19     }
20 
21     /*
22      * 插入排序方法
23      */
24     public void doInsertSort(){
25         for(int index = 1; index<length; index++){//外层向右的index,即作为比较对象的数据的index
26             int temp = array[index];//用作比较的数据
27             int leftindex = index-1;
28             while(leftindex>=0 && array[leftindex]>temp){//当比到最左边或者遇到比temp小的数据时,结束循环
29                 array[leftindex+1] = array[leftindex];
30                 leftindex--;
31             }
32             array[leftindex+1] = temp;//把temp放到空位上
33         }
34     }
35 
36     public static void main(String[] args){
37         int[] array = {38,65,97,76,13,27,49};
38         InsertSort is = new InsertSort(array);
39         System.out.println("排序前的为:");
40         is.display();
41         is.doInsertSort();
42         System.out.println("排序后的为:");
43         is.display();
44     }
45 }

 

posted @ 2021-03-17 14:59  wusirzzz  阅读(50)  评论(0)    收藏  举报