帮我生成一个冒泡算法用java实现
以下是Java实现冒泡排序的代码:
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 9, 1, 5, 6};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
冒泡排序的时间复杂度为O(n^2),在数据量较大时效率较低。
原文地址: https://www.cveoy.top/t/topic/tdP 著作权归作者所有。请勿转载和采集!