【发布时间】:2021-11-26 02:55:53
【问题描述】:
我不完全理解的唯一部分是内部 for 循环条件。在外部 for 循环中,我们声明 lastPos 是 array.length-1 ,所以如果我们要传递一个大小为 10 的数组,那么 lasPos 将等于 9 对吗?好的,现在在内部 for 循环中,我们说只要 index
//The IntBubbleSorter class provides a public static
//method for performing a bubble sort on an int array
public class IntBubbleSort
{
public static void main(String[] args)
{
int lastPosition;
int[] myArray = new int[10];
lastPosition = myArray.length-1;
System.out.println(lastPosition);
}
//The bubbleSort method uses the bubble sort algorithm
//to sort an int array
public static void bubbleSort(int[] array)
{
int lastPos; //Position of the last element to compare
int i; //index of an element to compare
int temp; //used to swap to elements
//The outer loop positions lastPos at the last element
//to compare during each pass through the array. Initially
//lastPos is the index of the last element in the array.
//During each iteration, it is decreased by one.
for(lastPos = array.length - 1; lastPos >=0 ; lastPos--)
{
//The inner loop steps through the array, comparing
//each element with its neighbor. All of the elements
//from index 0 through lastPos are involved in the
//comparison. If two elements are out of order, they
//are swapped
for(i = 0; i <= lastPos -1; i++) //what the hell?
{
//compare an element with its neighbor
if(array[i] > array[i -1])
{
//swap the two elements
temp = array[i];
array[i] = array[i+1];
array[i +1] = temp;
}
}
}
}
}
【问题讨论】:
-
用 3 或 4 个元素的数组在纸上手动写下算法。如果你发现这种方法有问题,或者有改进的余地,那么你可以把它带给你的教授并讨论它。提供的代码也可能是错误的
-
for(i = 0; i <= lastPos -1; i++)可以重写为for(i = 0; i < lastPos; i++),这是使用从零开始的数组索引的类 c 语言中普遍存在的模因
标签: java arrays algorithm for-loop bubble-sort