冒泡排序逻辑错误求助:基于Box类compareTo按体积升序排序失败
冒泡排序逻辑错误排查与修正
当前错误排序结果
Width: 3.2 height: 2.5 length: 9.1 Volume: 72.8 Width: 5.0 height: 4.8 length: 2.5 Volume: 60.0 Width: 67.8 height: 41.5 length: 56.1 Volume: 157848.57 Width: 20.5 height: 4.5 length: 80.75 Volume: 7449.1875 Width: 15.5 height: 44.2 length: 20.3 Volume: 13907.53 Width: 1.0 height: 1.0 length: 1.0 Volume: 1.0 Width: 14.23 height: 7.45 length: 10.5 Volume: 1113.14175 Width: 6.0 height: 5.0 length: 10.2 Volume: 306.0 Width: 7.5 height: 7.5 length: 7.5 Volume: 421.875 Width: 101.2 height: 32.5 length: 105.0 Volume: 345345.0
错误的冒泡排序实现
static void bubbleSort(Box[] theBoxes) { int n = theBoxes.length; for(int i = 0; i < n - 1; i++ ){ if(theBoxes[i].compareTo(theBoxes[i+1] ) > 0){ Box temp = theBoxes[i]; theBoxes[i] = theBoxes[i+1]; theBoxes[i + 1] = temp; }else if(theBoxes[i].compareTo(theBoxes[i+1] ) < -1){ Box temp = theBoxes[i+1]; theBoxes[i+1] = theBoxes[i]; theBoxes[i] = temp; } } }
不可修改的Box类代码
public class Box { private double width, height, length; Box(double w, double h, double l){ width=w; height=h; length=l; } private double getVolume(){ return width*height*length; } public int compareTo(Box o){ double myVol = this.getVolume(); double thatVol = o.getVolume(); if (myVol>thatVol) return 1; else if (myVol<thatVol) return -1; else return 0; } public String toString(){ return "Width: "+width+ "\theight: "+height+ "\tlength: "+length+ "\tVolume: "+getVolume(); } }
错误分析
- 缺少冒泡排序核心内层循环:原代码仅执行一轮相邻元素比较交换,冒泡排序需要外层循环控制排序轮数,内层循环遍历当前未排序元素,通过多次相邻交换才能将大元素逐步"冒泡"到末尾。
- 无效的compareTo判断条件:Box类的
compareTo方法仅返回-1、0、1三个值,compareTo(...) < -1的条件永远不会触发,属于冗余逻辑。 - 无提前终止机制:若某一轮遍历未发生任何交换,说明数组已完全有序,可提前退出循环减少不必要的计算。
修正后的冒泡排序代码
static void bubbleSort(Box[] theBoxes) { int n = theBoxes.length; // 外层循环控制排序轮数 for(int i = 0; i < n - 1; i++ ){ boolean swapped = false; // 内层循环遍历未排序区域,每轮减少i个已排序的末尾元素 for(int j = 0; j < n - 1 - i; j++){ // 当前元素体积大于下一个则交换 if(theBoxes[j].compareTo(theBoxes[j+1]) > 0){ Box temp = theBoxes[j]; theBoxes[j] = theBoxes[j+1]; theBoxes[j+1] = temp; swapped = true; } } // 本轮无交换则数组已完全有序,提前终止 if(!swapped){ break; } } }
内容的提问来源于stack exchange,提问作者pokemonmater940
相关产品推荐
相关产品推荐

