[英]How to sort an array in descending order comparing the first element and the last
I'm still a student and I have an assignment in Java where I have to sort an array that compares the first element from the last element until the array is sorted out from highest to lowest. 我还是一个学生,我在Java中有一个作业,我必须对一个数组进行排序,该数组将比较最后一个元素中的第一个元素,直到该数组从最高到最低进行排序。 I already did some of the algorithm but it seems it jumps swap number 2 and proceeds to swap3.
我已经做了一些算法,但似乎它会跳过交换编号2并继续进行swap3。 The program should run like this.
该程序应这样运行。
10 , 3, 7, 15, 9
10,3,7,15,9
10 , 3, 7, 15 , 9
10,3,7,15,9
15 , 3, 7 , 10, 9 - swap1
15,3,7,10,10 - swap1
15 , 3 , 7, 10, 9
15,3,7,10%,9
15, 3 , 7, 10, 9
15,3,7,10%,9
15, 9 , 7, 10 , 3 - swap2
15,9,7,10,3 - swap2
15, 10 , 7 , 9, 3
15,10,7,9,3-
15, 10, 7 , 9, 3
15,10,7,9,3-
15, 10, 7 , 9 , 3
15,10,7,9,3-
15, 10, 9, 7 , 3 - swap3
15,10,9,7,3 - swap3
15, 10, 9, 7, 3
15,10,9,7,3
So here is my algorithm doing this: 因此,这是我的算法:
public static void main(String[] args) {
int array[] = {10,3,7,15,9};
int f;
int l;
int temp;
System.out.println("Sorting array first and last elements");
for (f = 0; f < array.length; f++)
{
for (l = 4; l > f; l--)
{
if (array[f] < array[l])
{
temp = array[l];
array[l] = array[f];
array[f] = temp;
}
}
System.out.println("sorting....");
for (int c = 0; c < array.length; c++)
System.out.print(array[c] + ",");
}
System.out.println("sorted");
}
The output is: 输出为:
Sorting array first and last elements
排序数组的第一个和最后一个元素
sorting....
排序....
15,3,7,10,9,sorting....
15,3,7,10,9,排序....
15,10,7,9,3,sorting....
15,10,7,9,3,排序....
15,10,9,7,3,sorting....
15,10,9,7,3,排序....
15,10,9,7,3,sorting....
15,10,9,7,3,排序....
15,10,9,7,3,sorted
15,10,9,7,3,整理
It does sort but it jumps the swap number 2 and proceeds to swap number 3. How can i do this correctly that the output shows and does not jump the swap number 2? 它会排序,但会跳掉交换号2并继续进行到交换号3。我如何正确地执行此操作,以便输出显示而不跳出交换号2?
The outer loop goes from the first element until the end. 外循环从第一个元素到最后一个元素。
The inner loop goes from the last element until the index of the outer loop. 内循环从最后一个元素开始直到外循环的索引。
You print the content of the array after the inner loop runs. 内部循环运行后,您将打印数组的内容。 That is, you print the content one time per iteration of the outer loop.
也就是说,您在外循环的每次迭代中仅打印一次内容。 Keep in mind that during the inner loop, multiple swaps can happen.
请记住,在内部循环期间,可能会发生多次交换。 For example two swaps happen when
f=1
. 例如,当
f=1
时发生两次交换。
If you want to print the state after each swap, then do just that, in the inner loop: 如果要在每次交换后打印状态,请在内部循环中执行以下操作:
for (f = 0; f < array.length; f++) {
for (l = array.length - 1; l > f; l--) {
if (array[f] < array[l]) {
temp = array[l];
array[l] = array[f];
array[f] = temp;
System.out.println(Arrays.toString(array));
}
}
}
This will print: 这将打印:
[15, 3, 7, 10, 9]
[15, 9, 7, 10, 3]
[15, 10, 7, 9, 3]
[15, 10, 9, 7, 3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.