Java 實現插入排序,java插入排序

來源:互聯網
上載者:User

Java 實現插入排序,java插入排序

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;    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.