用Java泛型實現2-路插入排序

來源:互聯網
上載者:User
package ch10;/** * 2-路插入排序 * @author songjie * */public class TwoWayInsertSort {/** *  * @param <T> * @param t:原始數組 * @param s:待返回的排好序的數組 * @return * @throws IllegalArgumentException */public static <T extends Comparable> boolean twoWayInsertSort(T[] t, T[] s) throws IllegalArgumentException{if(t==null || t.length<=1) return true;//安全性檢查if(s==null || s.length!=t.length) throw new IllegalArgumentException("參數傳遞不正確-兩個數組的長度不一樣!");s[0] = t[0];int first = 0;int end = 0;for(int i=1 ; i<=t.length-1 ; i++){if(t[i].compareTo(s[0]) > 0){//插到後面int j;for(j=end; j>0 && s[j].compareTo(t[i])>0 ;j--){s[j+1] = s[j];}s[j+1] = t[i];end++;}else{//插到前面if(first == 0){first = s.length-1;s[first] = t[i];continue;}int k;for(k = first; k<=s.length-1 && s[k].compareTo(t[i])<=0 ; k++){s[k-1] = s[k];}s[k-1] = t[i];first--;}}return true;}public static void main(String[] args) {Integer[] arr = new Integer[]{7,4,3,1,6,9,8};Integer[] arrSort = new Integer[arr.length];TwoWayInsertSort.twoWayInsertSort(arr, arrSort);for(int i : arrSort){System.out.println(i);}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.