排序演算法代碼–Java

來源:互聯網
上載者:User

一、冒泡排序的Java實現

 

public void bubbleSort(int[] array){int len = array.length;int temp = 0;//迴圈次數:array.lengthfor(int i = 0; i < len; i ++){//每次迴圈體內將數組前len-i個數中最大的數移動到array[len-i-1]的位置上for(int j = 1; j < len - i; j ++){//此排序演算法為升序排序if(array[j - 1] > array[j]){temp = array[j -1];array[j -1] = array[j];array[j] = temp;}}}}

  

二、快速排序的Java實現

 

public void quickSort(int[] array){quickSort(array,0,array.length - 1);}private void quickSort(int[] array, int begin, int end){//如果數組為空白或只有一個元素,則結束if(begin >= end)return;int middle = partition(array,begin,end);quickSort(array, begin, middle - 1);quickSort(array, middle + 1, end);}private int partition(int[] array, int begin, int end){//以array[end]的值作為分界點,使得數組左邊的值都小於等於它,右邊的值都大於它int value = array[end];//i作為索引,它的下一個位置就是較大數的第一個位置int i = begin - 1;int temp = 0;for(int j = begin; j < end; j ++){if(array[j] <= value){i ++;temp = array[i];array[i] = array[j];array[j] = temp;}}i ++;array[end] = array[i];array[i] = value;return 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.