直接插入排序

------------恢复内容开始------------算法

直接插入排序算法从根本上讲就两步,第一步:将一个数组长度为n的数组的前i(i<n)个元素做为一个有序列,一共就有n-1个有序列。第二步:将第i+1个元素插入到这个有序列当中,比插入元素大的通通右移一位从而构成第n+1个有序列。数组

图示:测试

数组:  {22} 31 24 35 76 27 68 19 11
第一步:  {22 31}  24            
第二步:  {22  24  31}  35          
第三步:  {22  24  31  35}  76        
第四步:  {22  24  31  35  76}  27      
第五步:  {22  24  27  31  35  76}  68    
第六步:  {22  24  27  31  35 68   76}  19  
第七步:  {19  22  24  27  31  35  68  76}  11
第八步:  {11  19  22  24  27  31  35  68  76

算法代码:spa

 1 public class straightInsertSort {
 2         public void StraightInsertSort ( int data[], int a){      //a为数组长度
 3             for (int i = 1; i < a; i++) {         //第一步将数组分为n-1个有序列
 4                 if (data[i] < data[i - 1]) {       //若是索引为i的元素  比  有序列最大的元素即索引为i-1的元素大就没必要进行插入
 5                     int temp=data[i];             //储存要插入的元素
 6                     int j;                        //定义第一个循环里面的全局变量j
 7                     for (j = i - 1; j >= 0 && temp< data[j]; j--) {        //找到插入点
 8                         data[j + 1] = data[j];    //这一步后的j会减一而后跳出循环,此时的j即为插入点,所以下一步的插入点为j加一
 9                     }
10                     data[j + 1] = temp;    //以前定义全局变量j就是为了插入点的赋值,以前储存插入元素是由于以前的大的元素右移已经把插入元素的位置给占了,假如不提早取出来那么这个插入元素就会不见被这个有序列最大的元素替代
11                 }
12             }
13         }
14 }

测试代码:code

 1 public class straightInsertSortDemo {
 2     public static void main(String[] args) {
 3         int data[] = { 22, 31, 24, 35, 76, 27, 68, 19,11};
 4         straightInsertSort sis=new straightInsertSort();
 5         sis.StraightInsertSort(data,data.length);
 6         for(int i=0;i<data.length;i++) {
 7             System.out.print(data[i]+" ");
 8         }
 9     }
10 }

结果:blog

1 11 19 22 24 27 31 35 68 76 
2 Process finished with exit code 0

 

------------恢复内容结束------------排序

相关文章
相关标签/搜索