演算法:java實現氣泡排序
阿新 • • 發佈:2020-12-21
技術標籤:演算法
**
* @author dym
* @date 2020/12/20 13:20
*/
//氣泡排序,重的(數值大的在後面)靠近地面,輕的飄在空中(在上面)
public class BubbleSort {
public static void main(String[] args) {
//1.新建一個沒有排好序的陣列
int[] arr = new int[]{0,19,-2,13,8,21};
//2.輸出原陣列到控制檯
System.out.println("原陣列");
for (int a: arr) {
System.out.print(a+" ");
}
int temp;//交換數
//3.對原陣列進行氣泡排序
for (int i = 0; i < arr.length-1; i++) {
for (int j = 0; j < arr.length-1-i; j++) {
if (arr[j]<arr[j+1]){
temp = arr[j];
arr[ j] = arr[j+1];
arr[j+1] = temp;//把數值小的放在靠前位
}
}
}
System.out.println();
System.out.println("排好序的陣列");
//4.輸出排好序的陣列
for (int a: arr) {
System.out.print(a+" ");
}
}
}
執行結果: