简体   繁体   English

在Java中使用排序算法

[英]Using a sort algorithm in Java

I was trying to use a sort algorithm according to our programming lecture. 我尝试根据我们的编程讲座使用排序算法。 Maybe I am just missing something. 也许我只是想念一些东西。

I would appreciate it if someone may help me out or could give me a hint about any mistake I made. 如果有人可以帮助我或者给我一些关于我犯的错误的提示,我将不胜感激。

Here my current code: 这是我当前的代码:

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;
}
}

You are doing an in-place selection sort . 您正在执行就地选择排序 Change 更改

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

to

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

Also change 也改变

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

to

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

Additionally, because i and j are declared within your for condition, they are only accessible within the scope of the for loop . 此外,由于i和j是在您的for条件中声明的, 因此只能在for循环的范围内访问它们 Instead, declare them outside of your loops. 而是在循环之外声明它们。

Lastly, it's a good idea to check if(smallestIndex != i) before swapping them. 最后,最好在交换它们之前检查if(smallestIndex != i)

So here's your working code , assuming your swap function works correctly. 因此,这是您的工作代码 ,假设您的交换功能正常工作。

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;
}
}

Please refer to the following: http://en.wikipedia.org/wiki/Selection_sort 请参考以下内容: http : //en.wikipedia.org/wiki/Selection_sort

Here is my implementation of the swap command (sorry for wrong declarations I have recognized them and I will change them immediately!): 这是我对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;

}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM