java實現排序

來源:互聯網
上載者:User

標籤:演算法   排序   Algorithms   

public class SortDemo {//private static long[] arr = {6,5,2,7,1,8,4,3};private static long[] arr = {1,2,3,4,5,6,7,8};private static int count = 0;/** * 冒泡排序 * O(n2) */public static void bubble(){long temp = Long.MIN_VALUE;int len = arr.length;for(int j = 0;j<len;j++){for(int i = 0;i<len-1;i++){if(arr[i]>arr[i+1]){temp = arr[i+1];arr[i+1] = arr[i];arr[i] = temp;}}}}/** * 選擇排序 * O(n2) */public static void select(){int len = arr.length;long temp = Long.MIN_VALUE;int index = 0;for(int j = 0;j<len;j++){index = j;for(int i = j;i<len;i++){if(arr[i]<arr[index]){index = i;}}temp = arr[j];arr[j] = arr[index];arr[index] = temp;print();}}/** * 插入排序 * O(n2) */public static void insert(){int len = arr.length;long temp;for(int i=1;i<len;i++){int j = i-1;temp = arr[i];while(j>=0 && temp<arr[j]){arr[j+1] = arr[j];j--;}arr[j+1] = temp;print();}}/** * 快速排序 * O(N*longN) */public static void quick(){quick(arr);print();}private static long[] quick(long[] a){if(a.length<=1)return a;long temp = 0;int index = 0;for(int i = 0;i<a.length-1;i++){if(a[i]<a[a.length-1]){temp = a[i];a[i] = a[index];a[index++] = temp;}}temp = a[a.length-1];a[a.length-1] = a[index];a[index] = temp;if(index==0)return a;long[] temp1 = new long[index];long[] temp2 = new long[a.length-index-1];System.arraycopy(a, 0, temp1, 0, index);System.arraycopy(a, index+1, temp2, 0, a.length-index-1);System.arraycopy(quick(temp1), 0, a, 0, index);System.arraycopy(quick(temp2), 0, a, index+1, a.length-index-1);return a;}/** * 歸併排序 * O(N*longN) */public static void merge (){arr = merge(arr);print();}private static long[] merge(long[] a){long[] c = new long[a.length];int mid = a.length/2;long[] temp1 = new long[mid];long[] temp2  = new long[a.length-mid];if(mid>1){System.arraycopy(a, 0, temp1, 0, mid);System.arraycopy(a, mid, temp2, 0, a.length-mid);temp1 = merge(temp1);temp2 = merge(temp2);System.arraycopy(temp1, 0, a, 0, mid);System.arraycopy(temp2, 0, a, mid, a.length-mid);}int i=0,j=mid,index=0;while(i<mid && j<a.length && index<a.length-1){if(a[i]<a[j]){c[index++] = a[i++];}else{c[index++] = a[j++];}}while(index<a.length && i<mid){c[index++] = a[i++];}while(index<a.length && j<a.length){c[index++] = a[j++];}return c;}public static void print(){for(long v:arr){System.out.print(v);}System.out.println();}public static void main(String[] args) {quick();}}


java實現排序

聯繫我們

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