优化这段代码 public static Object[] bubbleSort(Object []sort){ for(int i=1;i<sort.length;i++){ for(int j=0;j<sort.length-i;j++) { if((Integer)sort[j]>(Integer)sort[j+1]) { Object temp=sort[j]; sort[j]=sort[j+1]; sort[j+1]=temp; } } } return sort; }
时间: 2023-05-24 10:05:28 浏览: 46
public static Object[] bubbleSort(Object[] sort){
for(int i=1;i<sort.length;i++){ //修改:i++
for(int j=0;j<sort.length-i;j++){ //修改:j++
if((Integer)sort[j]>(Integer)sort[j+1]){ //修改:j+1
Object temp=sort[j];
sort[j]=sort[j+1];
sort[j+1]=temp;
}
}
}
return sort;
}
相关问题
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; } } } }添加注释
/**
* 冒泡排序
* @param 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;
}
}
}
}
public class BubbleSort { 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]) { // swap arr[j+1] and arr[j] int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } public static void main(String[] args) { int[] arr = {64, 34, 25, 12, 22, 11, 90}; bubbleSort(arr); System.out.println("Sorted array:"); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } }}优化
冒泡排序的时间复杂度为 O(n^2),如果数据量较大,排序的时间会很慢。下面介绍两种优化方法:
1. 如果在一次外循环中,没有发生任何交换,则说明数组已经有序,可以提前结束排序。
2. 在内循环中,记录最后一次交换的位置,该位置后面的元素已经有序,下一次内循环只需要遍历到这个位置即可。
优化后的代码如下:
```
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
boolean flag = true; // 标记是否发生交换
int lastIndex = n - 1; // 记录最后一次交换的位置
for (int j = 0; j < lastIndex; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = false;
lastIndex = j; // 更新最后一次交换的位置
}
}
if (flag) { // 如果没有发生交换,说明已经有序,提前结束排序
break;
}
}
}
```