java定义一个整型数组实现冒泡排序算法
以下是一个使用Java实现冒泡排序算法的例子:
public class BubbleSort {
public static void main(String[] args) {
int[] array = {5, 2, 8, 1, 4};
bubbleSort(array);
// 打印排序后的数组
for (int num : array) {
System.out.print(num + " ");
}
}
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n-1; i++) {
// 每次遍历将最大的数冒泡到最右侧
for (int j = 0; j < n-i-1; j++) {
if (array[j] > array[j+1]) {
// 交换相邻的两个元素
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
}
输出结果为: 1 2 4 5 8
原文地址: https://www.cveoy.top/t/topic/jaJV 著作权归作者所有。请勿转载和采集!