package com; public class Paixu { static boolean flag=true; public static void main(String[] args) { // TODO Auto-generated method stub int[] a = random(50000); long l1 = System.currentTimeMillis(); insertion_Sort(a); long l2 = System.currentTimeMillis(); System.out.println("插入排序用时:"+(l2-l1)); check(a); } // 插入排序 private static int[] insertion_Sort(int[] a){ /* for (int i = 1; i < a.length; i++) { int temp = a[i]; for (int j = i-1; j >= 0; j--) { if (a[j] > temp) { a[j+1] = a[j]; if (j==0) { a[0]=temp; } }else { a[j+1] = temp; break; } } }*/ // 优化插入排序算法 for(int i=1;i<a.length;i++){ int temp=a[i]; int j; for(j=i-1;j>=0;j--) { if(a[j]>temp) { a[j+1]=a[j]; }else { break; } } a[j+1]=temp; } /* int i,j; int n=a.length; for (i=1;i<n;i++) { j = i; int target = a[i]; while (j>0 && target<a[j-1]) { a[j] = a[j-1]; j--; } a[j] = target; }*/ System.out.println("***********************"); return a; } public static int[] random(int num) { long start = System.currentTimeMillis(); int[] a ; a = new int[num]; for (int i = 0; i < num; i++) { int rand = (int) Math.round(Math.random()*num*100); a[i] = rand; } long end =System.currentTimeMillis(); System.out.println("产生"+num+"个随机数花费时间=====>"+(end-start)+"毫秒"); return a; } private static boolean check (int[] a) { for (int i = 0; i < a.length-1; i++) { if (a[i+1] < a[i]) { flag = false; } } System.out.println(flag); return flag; } }