【JAVA】java常見排序演算法

來源:互聯網
上載者:User
/** *  * @author Loger *  */public class Sort {/** * 選擇排序 * @param array * @return */public int[] SelectSort(int array[]){int out,in;int min;for(out = 0; out < array.length-1; out++){min = out;for(in = out+1; in < array.length; in++){if(array[in] < array[min]){min = in;}}if(min != out){array[out] = array[out] + array[min];array[min] = array[out] - array[min];array[out] = array[out] - array[min];}}return array;}/** * 冒泡排序 * @param array * @return */public int[] BubbleSort(int array[]){for(int i=0; i < array.length - 1; i++){for(int j = i; j < array.length-i-1; j++){if(array[j] > array[j+1]){array[j] = array[j] + array[j+1];array[j+1] = array[j] - array[j+1];array[j] = array[j] - array[j+1];}}}return array;}/** * 插入排序 * @param array * @return */public int[] InsertSort(int array[]){for(int i=1; i < array.length; i++){int insert = array[i];//待插入的元素int j = i - 1;while(j >= 0 && insert < array[j]){array[j+1] = array[j];j--;}array[j+1] = insert;}return array;}/** * 主函數 * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint [] array = {1,3,2,9,8,7,10};Sort sort = new Sort();System.out.println("原數組:");for(int a:array){System.out.print(a+" ");}//System.out.println("\n選擇排序:");//for(int a:sort.SelectSort(array)){//foreach列印數組//System.out.print(a+" ");//}//System.out.println("\n冒泡排序:");//for(int a:sort.BubbleSort(array)){//foreach列印數組//System.out.print(a+" ");//}System.out.println("\n插入排序:");for(int a:sort.InsertSort(array)){//foreach列印數組System.out.print(a+" ");}}}

 

聯繫我們

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