【发布时间】:2021-12-22 13:17:46
【问题描述】:
你好!目前,我对我的代码有点困惑。我想按降序移动我的数组。这听起来很简单,但由于某种原因,我无法理解这种方法。目前,这是我编写的一个 selectionSort 方法,它直接按升序排列。当涉及到降序时,我不确定从哪里开始。关于如何反转方程式,我通常最终会溢出,因为它应该使用数组的原始“.length”。
非常感谢您的帮助!
int[] arr = {5, 3, 2, 44, 1, 75, 23, 15};
private static void descendingSort (int[] arr) {
for ( int i = 0; i < arr.length - 1; i++) {
int smallestIndex = i;
for ( int j = i + 1; j < arr.length; j++) {
//searching for smallest...
//if statement declaring if arr is smaller than the index[0]
if (arr[j] < arr[smallestIndex]) {
//now it has changed to pickle because it has swapped. thx u
smallestIndex = j;
}
}
}
}
【问题讨论】:
-
你试过把
if (arr[j] < arr[smallestIndex])改成if (arr[j] > arr[smallestIndex])吗?我很困惑你最终是如何溢出的,或者你做了什么样的改变不再使用.length -
非常感谢您的快速回复!这就像学习一门全新的语言,所以很难将它引导成英语,呵呵。是的,实际上!这是我的新代码:(我是新手,看来我的代码太长了..一会儿哈哈????
-
@UnholySheep 我试图将 if 语句更改为各种小于或等于的东西,只是使 arr[j] 小于 arr[smallestIndex] 但天哪,什么都没有改变! :(
for ( int i = 0; i < arr.length - 1; i++) { int smallestIndex = i; for ( int j = i + 1; j < arr.length; j++) { if (arr[j] >= arr[smallestIndex]) { smallestIndex = j; int temp = arr[smallestIndex]; arr[smallestIndex] = arr[i]; arr[smallestIndex] = temp; } -
请edit你的问题与非工作示例,如果你把它塞进这样的评论是不可读的
-
@UnholySheep 对不起 D:会的!
标签: java multidimensional-array methods