Java 气泡排序交换法
我一直在学习一门关于冒泡排序的课程,但swap方法实现的一部分一直困扰着我。对我来说没有意义的部分,希望有人能澄清,与关于指数的比较有关Java 气泡排序交换法,java,algorithm,sorting,bubble-sort,Java,Algorithm,Sorting,Bubble Sort,我一直在学习一门关于冒泡排序的课程,但swap方法实现的一部分一直困扰着我。对我来说没有意义的部分,希望有人能澄清,与关于指数的比较有关 public static void main(String[] args) { int[] intArray = {20, 35, -15, 7, 55, 1, -22}; //start at index 6 which is -22 value; as long as the length of the array is
public static void main(String[] args) {
int[] intArray = {20, 35, -15, 7, 55, 1, -22};
//start at index 6 which is -22 value; as long as the length of the array is more than 0; decrement down to the first index
for (int lastUnsortedIndex = intArray.length -1; lastUnsortedIndex > 0; lastUnsortedIndex -- ){
//i=0; as long as i is less than length of intArray -1, so 6; i++
for(int i =0; i< lastUnsortedIndex; i++){
//if value at index i is more than value at index i+1
if(intArray[i] > intArray[i +1]){
//swap their positions
swap(intArray, i , i+1);
}
}
}
for(int num : intArray){
System.out.println(num);
}
}
//for swapping
public static void swap (int[] array , int i , int j){
System.out.println("i= "+i);
System.out.println("j= "+j);
if(i == j){ // if they are the same then just return
return;
}
int temp = array[i];// need the temporary variable to hold value at position i because
//... we are going to swap array[i] with j, but still need to retain the value so we can assign it to array[j]
array[i] = array[j];
array[j] = temp;
}
publicstaticvoidmain(字符串[]args){
int[]intArray={20,35,-15,7,55,1,-22};
//从索引6开始,该索引的值为-22;只要数组的长度大于0,则递减到第一个索引
对于(int lastUnsortedIndex=intArray.length-1;lastUnsortedIndex>0;lastUnsortedIndex--){
//i=0;只要i小于数组-1的长度,则为6;i++
对于(int i=0;iintArray[i+1]){
//交换立场
互换(内部,i,i+1);
}
}
}
for(int num:intArray){
系统输出打印项数(num);
}
}
//交换
公共静态无效交换(int[]数组,int i,int j){
System.out.println(“i=“+i”);
System.out.println(“j=“+j”);
如果(i==j){//如果它们是相同的,则返回
返回;
}
int temp=array[i];//需要临时变量将值保存在位置i,因为
//…我们将用j交换数组[i],但仍然需要保留该值,以便将其分配给数组[j]
数组[i]=数组[j];
数组[j]=温度;
}
如你所见,如果(i==j){return;}似乎只有在我没有弄错的情况下才会比较索引。为什么还要费心做这个检查?似乎我永远都不会等于i+1,除非我在这里遗漏了什么?没有理由进行检查。将
i+1
传递到swap
也是毫无意义的。只需传递i
,然后将j
替换为i+1
。不要担心检查是否相等。如果您关心速度,请删除打印语句。为什么还要费事进行此检查?
这是一个小优化。如果i==j,那么它就是同一个对象,显然不需要交换。尽管我怀疑它是否真的“有效”。交换本身只是交换两个整数(Java没有复制构造函数,也不会复制堆内存,除非你非常努力)。所以做一个比较和分支实际上可能会使代码变慢。我怎么能和j相等呢?J被设定为i+1@JessicaJones你说得对。在您发布的代码中不需要检查i==j
,因为冒泡排序永远不会尝试将元素与自身交换。一个可能的算法示例是Fisher-Yates洗牌。因此,如果这只是一个通用的可重用的交换函数,您的专家可以将其用于所有操作,那么这是可以理解的。但是,它可能会使代码变慢,即使是对于i
和j
可能相等的代码。@WJS YAGNI,Jessica Jones是对的,这在这里没有意义