java — 排序演算法

來源:互聯網
上載者:User

標籤:區分   對比   alt   swa   out   ima   package   swap   第一個   

1.冒泡排序

  比較相鄰元素,如果第一個比第二個大,就交換位置,每一次交換,當前

package BubbleSort;public class Test {public static void main(String[] args){int[] arr = {1,3,5,7,3,6,7,4,8,34,6};Test test = new Test();test.bubbleSort(arr);for(int i = 0; i < arr.length; i++){System.out.print(arr[i] + " ");}}public void bubbleSort(int[] num){int temp = 0;for(int i = 0; i < num.length - 1; i++){for(int j = i + 1; j < num.length; j++){if(num[j-1] > num[j]){temp = num[j];num[j] = num[j - 1];num[j - 1] = temp;}}}}}

  

 

 

2. 選擇排序

  從所有的數字中找到最小的數,放在第一個位置,然後從剩餘的數字中找出次小的數,放在第二個位置,然後從剩下的數字中找出再次小的數,放在第三個位置......以此類推,直到所有的資料全部有序。

package SelectionSort;public class Test {public static void main(String[] args){int[] a = {4,2,1,6,3,6,0,-5,4,3};Test test = new Test();test.selectionSort(a);for(int i = 0; i < a.length; i++){System.out.print(a[i] + " ");}}public void selectionSort(int[] source){for(int i = 0; i < source.length; i++){for(int j = i + 1; j < source.length; j++){if(source[i] > source[j]){swap(source, i, j);}}}}private void swap(int[] source, int x, int y){int temp = source[x];source[x] = source[y];source[y] = temp;}}

  注意將選擇排序和冒泡排序進行區分:冒泡排序是將相鄰的資料進行對比,而選擇排序是將下標為i和j的資料進行對比(每次選出當前資料集中最小的)。

 

 

 

 

 

 

 

 

 

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.