【问题标题】:How to write a selectionSort method going in Descending order?如何编写按降序排列的 selectionSort 方法?
【发布时间】: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] &lt; arr[smallestIndex])改成if (arr[j] &gt; arr[smallestIndex])吗?我很困惑你最终是如何溢出的,或者你做了什么样的改变不再使用.length
  • 非常感谢您的快速回复!这就像学习一门全新的语言,所以很难将它引导成英语,呵呵。是的,实际上!这是我的新代码:(我是新手,看来我的代码太长了..一会儿哈哈????
  • @UnholySheep 我试图将 if 语句更改为各种小于或等于的东西,只是使 arr[j] 小于 arr[smallestIndex] 但天哪,什么都没有改变! :(for ( int i = 0; i &lt; arr.length - 1; i++) { int smallestIndex = i; for ( int j = i + 1; j &lt; arr.length; j++) { if (arr[j] &gt;= arr[smallestIndex]) { smallestIndex = j; int temp = arr[smallestIndex]; arr[smallestIndex] = arr[i]; arr[smallestIndex] = temp; }
  • edit你的问题与非工作示例,如果你把它塞进这样的评论是不可读的
  • @UnholySheep 对不起 D:会的!

标签: java multidimensional-array methods


【解决方案1】:

如果您想快速解决问题,请按照以下方法解决。 请注意,我们只更改了几行。

具体...

  1. 我们仍然找到最小的元素
  2. 我们把它放在后面而不是前面
  3. 两个循环中的迭代顺序是back-to-front 而不是front-to-back

实现这一点的更简单方法是按升序对元素进行排序,然后反转数组。

 void selectionSortDescending(int arr[])
    {
        int n = arr.length;

        // Start by finding the smallest element to put in the very back
        // One by one move boundary of unsorted subarray
        for (int i = n-1; i >= 0; i--)
        {
            // Find the minimum element in unsorted array
            int min_idx = i;
            for (int j = i-1; j >= 0; j--)
                if (arr[j] < arr[min_idx])
                    min_idx = j;
 
            // Swap the found minimum element with the last element
            int temp = arr[min_idx];
            arr[min_idx] = arr[i];
            arr[i] = temp;
        }
    }

【讨论】:

  • 哇!!!!是的,就是这样!对于您的快速回复,我非常感谢您和绵羊,我真的很感激!我似乎有问题的一个原因是在开始其他任何事情之前将最小的元素推回去。特别是对于那个 i-1,我认为这是我遇到溢出错误的地方。谢谢!
  • 任何时候,兄弟 ;)
  • 你大佬 :)))
  • 啊哈哈哈......我很高兴听到这个消息。
猜你喜欢
  • 1970-01-01
  • 2019-08-07
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-10
  • 2021-02-26
相关资源
最近更新 更多