【问题标题】:Using a sort algorithm in Java在 Java 中使用排序算法
【发布时间】:2015-01-03 18:49:43
【问题描述】:

我试图根据我们的编程讲座使用排序算法。也许我只是错过了一些东西。

如果有人可以帮助我或就我犯的任何错误给我提示,我将不胜感激。

这是我当前的代码:

package Sortieralgorithmus;

public class sort {

public static int[] straightSelection(int[] numbers) {

    for (int i = 0; i < numbers.length; i++) {
        int smallestIndex = i;

        for (int j = i + 1; j < numbers.length; j++) {
            if (numbers[i] < numbers[smallestIndex]) {
                smallestIndex = j;
            }
        }
        swap(j, i, numbers);


    }

    return numbers;
}
}

【问题讨论】:

  • 欢迎来到 Stack Overflow!你的代码能运行吗?你得到什么错误?代码在运行时会做什么?你想让它做什么?您必须确保解决所有这些问题,我们才能为您提供帮助……否则,我们甚至不知道您在问什么。
  • 什么不起作用?
  • 1) 有什么问题? 2) 使用 Java 代码约定使您的代码更易于阅读;包是小写的,类以大写字母开头。
  • 您是否在任何地方定义了swap?你在两个地方混淆了ijsmallestIndex

标签: java algorithm sorting swap


【解决方案1】:

您正在执行就地选择排序。 改变

if (numbers[i] < numbers[smallestIndex]) 

if (numbers[j] < numbers[smallestIndex]) 

也改变

(int i = 0; i < numbers.length; i++)

(int i = 0; i < numbers.length()-1; i++)

此外,由于 i 和 j 在 for 条件中声明,它们只能在 for 循环范围内访问。相反,在循环之外声明它们。

最后,在交换之前检查if(smallestIndex != i) 是个好主意。

这是你的工作代码,假设你的交换功能正常工作。

package Sortieralgorithmus;

public class sort {

public static int[] straightSelection(int[] numbers) {
int i, j;  // declare them here 
int smallestIndex; //declare it here as well

for (i = 0; i < numbers.length-1; i++) {
    smallestIndex = i;

    for (j = i + 1; j < numbers.length; j++) {
        if (numbers[j] < numbers[smallestIndex]) {
            smallestIndex = j;
        }
    }
    if(smallestIndex != i){
    swap(smallestIndex, i, numbers);
    }

}

return numbers;
}
}

请参考以下内容:http://en.wikipedia.org/wiki/Selection_sort

【讨论】:

  • 所以看起来它正在工作,但是当我运行它时,我得到一个空控制台,为什么我需要一个对象来检索方法直接选择?因为如果我尝试在没有它的情况下检索它,它会说:“对于 Workflow 类型的方法 straightSelection(int[]) 是未定义的”
  • 抱歉,它是这样说的:“Sort 类型的静态方法 StraightSelection(int[]) 应该以静态方式访问”
  • @DevSEDominik 删除 static 修饰符应该可以解决这个问题。
  • 我所做的只是:“[I@15db9742”
  • collabedit.com/bb899 好的,将您的代码复制并粘贴到那里,我会看看。 @DevSEDominik
【解决方案2】:

这是我对 swap 命令的实现(抱歉声明有误,我已经认出了它们,我会立即更改它们!):

package Sortieralgorithmus;

public class Swap {

public static void swap(int a, int b, int []numbers) {

    int temp = numbers[a];
    numbers[a] = numbers[b];
    numbers[b] = temp;

}

}

【讨论】:

猜你喜欢
  • 2011-10-17
  • 1970-01-01
  • 2011-05-14
  • 1970-01-01
  • 2019-10-23
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 2013-09-04
相关资源
最近更新 更多