冒泡排序
1.冒泡排序思想
讓數組當中相鄰的兩個數進行比較,數組當中比較小的數值向下沉,數值比較大的向上浮!外層for循環控制循環次數,內層for循環控制相鄰的兩個元素進行比較。
2. 編碼
package com.zhmcode.bubblesort;
/**
* Created by zhmcode on 2019/2/15 0015.
*/
public class MyBubbleSort {
public static void main(String[] args) {
int[] arr = {3, 2, 5, 1, 8, 1, 11, 8};
int[] results = bubbleSort(arr);
for(int item : results){
System.out.print(item + " ");
}
}
/**
* 冒泡排序,升序排列
* 數組當中比較小的數值向下沉,數值比較大的向上浮!
*/
public static int[] bubbleSort(int[] arr) {
// 外層for循環控制循環次數
for(int i=0;i<arr.length;i++){
int tem = 0;
// 內層for循環控制相鄰的兩個元素進行比較
for(int j=i+1;j<arr.length;j++){
if(arr[i]>arr[j]){
tem = arr[j];
arr[j]= arr[i];
arr[i] = tem;
}
}
}
return arr;
}
}