使用Java中的排序算法 [英] Using a sort algorithm in Java
问题描述
我是想根据我们的编程讲座使用排序算法。也许我只是失去了一些东西。
我会AP preciate,如果有人可以帮助我还是可以给我一个大概的任何错误,我做了提示。
下面我目前的code:
包Sortieralgorithmus;
公共类排序{
公共静态INT [] straightSelection(INT []号){
的for(int i = 0; I< numbers.length;我++){
INT smallestIndex =我;
对于(INT J = I + 1; J< numbers.length; J ++){
如果(数字[1] - ;数字[smallestIndex]){
smallestIndex = j的;
}
}
掉期(J,I,数字);
}
返回的数字;
}
}
您正在做的就地选择排序。 更改
如果(数字[1] - ;数字[smallestIndex])
到
如果(号码[J] LT;数字[smallestIndex])
也改变
(INT I = 0; I< numbers.length;我++)
到
(INT I = 0; I< numbers.length() - 1;我++)
此外,由于i和j在你的宣布参加
条件,他们只的范围for循环中访问。相反,声明它们的循环之外。
最后,这是一个好主意,检查如果(smallestIndex!= 1)
交换之前。
因此,这里是你的工作code ,假设您的交换功能的正常工作。
包Sortieralgorithmus;
公共类排序{
公共静态INT [] straightSelection(INT []号){
INT I,J; //这里声明它们
INT smallestIndex; //声明它在这里也
对于(i = 0; I< numbers.length-1;我++){
smallestIndex =我;
为(J = I + 1; J< numbers.length; J ++){
如果(号码[J] LT;数字[smallestIndex]){
smallestIndex = j的;
}
}
如果(smallestIndex!=ⅰ){
掉期(smallestIndex,我,号码);
}
}
返回的数字;
}
}
请参阅以下内容: http://en.wikipedia.org/wiki/Selection_sort
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. Instead, declare them outside of your loops.
Lastly, it's a good idea to check if(smallestIndex != i)
before swapping them.
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
这篇关于使用Java中的排序算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!