8 java
使用第三个变量来交换数字需要什么?对不起,但是我没理解.
这是我根据每个元素的长度排序数组元素的示例代码.正如你在这里看到的,我正在使用第三个变量,并交换数组的元素.我有一个不同的实现这个程序,但我在网上找到了以下的例子,并想了解什么是交换有用的?如果有人可以向我解释,那就太好了.
public class StringSort {
public static void main(String[] args) {
String[] arr = new String[] { "abcd", "dexter", "stringsortexample", "fruit", "apple","car" };
compareArrayElements(arr);
System.out.println("The strings in the sorted order of length are: ");
for (String sortedArray : arr) {
System.out.println(sortedArray);
}
}
public static void compareArrayElements(String[] arr) {
String temp = "";
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i+1; j < arr.length; j++) {
if (arr[i].length() > arr[j].length())
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*n C 23
The short answer is that you can't juggle in Java!
Think of each variable as a hand that can "hold" one value; e.g. a ball.
If you have two hands and two balls, the only way to switch the balls to the opposite hands involves throwing one of the balls up in the air (or something like that). But there is no "throw a value into the air" operation in Java.
If you can't juggle you need a third hand (or some other temporary holding place) to swap the balls. And in Java terms, that means a temporary variable.
For the record, I found this analogy very useful when I was learning to program. But don't take it too far :-).
(In fact, if we are talking about integers, there is a mathematical trick that you can use to swap numbers ... involving XOR ... but it doesn't work in general.)
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
Run Code Online (Sandbox Code Playgroud)
这是交换的一部分.如果没有临时的临时变量,您将失去信息.
示例:int a = 5,b = 10;
现在交换a和b没有temp:a = b; - > a = 10,b = 10 - > 5丢失无法检索或获取它.或者让我们试试:b = a; - > a = 5,b = 5 - > 10丢失,无法检索它.
随着临时:
而已.临时变量存储一个变量的原始状态,因为当变量被赋予其新状态(或值)时,该状态被覆盖并丢失.
在您的示例中,您使用交换来更改具有多个不同位置的数字(信息)的位置.在这里,您有一个排序算法,属于选择排序类别(而不是冒充其他答案建议的排序).
在Bubble Sort链接中观看动画图像,您可以了解交换,然后查看Selection Sort链接以了解这里发生了什么.
在您的代码示例中,算法会检查第一个位置,并将其与数组中的任何其他位置进行比较.如果它在第一个位置找到一个较小的值作为当前值,则它会交换两个数字.在外循环的一次迭代之后(内循环第一次完全完成),数组中的第一个位置保持整个数组中的最小值,因为如果它更大,则它与较小的一个交换,如果你测试了所有它上面的值包含最小的值.
在循环中的下一次运行(i = 0 ++ = 1)中,针对第二位置(i = 1)测试阵列的其余部分(i + 1 = 2).因此在第二次迭代后索引1(arr 1)包含第二个最小数字(和索引0,arry [0]包含最小的数字).这样做直到以这种方式处理数组的所有索引 - 实际上最后一个不能与其他索引一起检查,因为它确实是最后一个 - 因此数组被排序.