Java 此选择排序代码有什么问题?
我被要求做一个选择排序算法,但它不起作用,我不知道为什么。代码如下:Java 此选择排序代码有什么问题?,java,algorithm,sorting,selection-sort,Java,Algorithm,Sorting,Selection Sort,我被要求做一个选择排序算法,但它不起作用,我不知道为什么。代码如下: int count = 0; int count2; int min; int size = scan.nextInt(); int temp = 0; int[] numbers = new int[size]; while (count < size) { numbers[count] = scan.nextInt(); cou
int count = 0;
int count2;
int min;
int size = scan.nextInt();
int temp = 0;
int[] numbers = new int[size];
while (count < size) {
numbers[count] = scan.nextInt();
count ++;
}
count = 0;
while (count < size) {
count2 = size;
min = numbers[count];
while (count < count2) {
count2 --;
if (numbers[count2] < numbers[min]) {
min = count2;
}
}
temp = numbers[temp];
numbers[temp] = numbers[count];
numbers[count] = temp;
count ++;
}
count = 0;
while (count < size) {
System.out.println(numbers[count]);
count ++;
}
}
int count=0;
int count2;
int-min;
int size=scan.nextInt();
内部温度=0;
int[]数字=新的int[大小];
while(计数<大小){
numbers[count]=scan.nextInt();
计数++;
}
计数=0;
while(计数<大小){
count2=大小;
最小值=数字[计数];
而(计数<计数2){
第二条--;
如果(数字[count2]<数字[min]){
min=count2;
}
}
温度=数字[温度];
数字[温度]=数字[计数];
数字[计数]=温度;
计数++;
}
计数=0;
while(计数<大小){
System.out.println(数字[计数]);
计数++;
}
}
输入:
10
1.
0
2.
9
3.
8.
4.
7.
5.
六,
输出:
1.
2.
9
8.
3.
3.
8.
4.
7.
四,
再看看这段代码
如果您在第一个输入为11的位置运行此操作,则会出现索引超出范围的错误
特别是,您计划用
temp=numbers[temp]
实现什么?您将temp分配给一个基本上是任意的数字,因为数字[0]
可以是任何数字。在输出中获得重复值(输入中没有)这一事实意味着您的交换不起作用,因此:
temp = numbers[temp];
numbers[temp] = numbers[count];
numbers[count] = temp;
这是错误的
它应该是min
,而不是temp
:
temp = numbers[min];
numbers[min] = numbers[count];
numbers[count] = temp;
下面是一个算法,它可以工作并利用java中for的强大功能。要浏览数组或列表,可以对(int current:array)执行
这比使用while或for更方便
int min;
int mem = 0;
int size = 11;
int [] numbers = {10, 1, 0, 2, 9, 3, 8, 4, 7, 5, 6};
for (int i=0; i<size-1; i++){
min =i;
for(int j=i+1; j<size; j++){
if (numbers[j]<numbers[min]){
min = j;
}
}
// swap
mem= numbers[i];
numbers[i] = numbers[min];
numbers[min] = mem;
}
for (int toPrint : numbers){
System.out.println(toPrint);
}
}
int-min;
int-mem=0;
int size=11;
int[]数字={10,1,0,2,9,3,8,4,7,5,6};
对于while循环中的(inti=0;i),您尝试使用numbers[0]元素作为numbers[]numbers[min]
min = numbers[count]; \\min is value of first element of numbers[]
while (count < count2) {
count2 --;
if (numbers[count2] < numbers[min]) { \\ you try to use value of numbers[0] element as index of numbers[] aray.
min = count2;
}
min=numbers[count];\\min是数字的第一个元素的值[]
而(计数<计数2){
第二条--;
如果(numbers[count2]
将if(数字[count2]
替换为if(数字[count2]
你想免费获得有价值的提示吗?使用调试器!遵循调试器,你会更好..更好..理解你的代码和错误。这可能是我见过的最复杂的选择排序。看起来for循环比大多数while循环更好。
min = numbers[count]; \\min is value of first element of numbers[]
while (count < count2) {
count2 --;
if (numbers[count2] < numbers[min]) { \\ you try to use value of numbers[0] element as index of numbers[] aray.
min = count2;
}