直接插入排序

来源:互联网 发布:nginx 支持websocket 编辑:程序博客网 时间:2024/06/05 07:13
//直接插入排序://直接插入排序是由两层嵌套循环组成的。//外层循环标识并决定待比较的数值。//内层循环为待比较数值确定其最终位置。//直接插入排序是将待比较的数值与它的前一个数值进行比较,//所以外层循环是从第二个数值开始的。//当前一数值比待比较数值大的情况下继续循环比较,//直到找到比待比较数值小的并将待比较数值置入其后一位置,//结束该次循环   public class Straight{public static void main(String args[]){ int[] a = { 46, 58, 15, 45, 90, 18, 10, 62 }; int n = a.length ; int i, j ; for (i = 0; i < n; i++ ) {    int temp = a[i] ;    for (j = i ; j > 0 && temp < a[j-1] ; j-- ){      a[j] = a[j - 1];     }     a[j] = temp ;       }   for(i=0; i<n; i++){     System.out.print(a[i]+"\t");    }  } }//直接插入排序属于稳定的排序,时间复杂性为o(n^2),空间复杂度为O(1)。