为什么我的选择排序算法不执行应有的功能(java)? [英] Why doesn't my selection sort algorithm do what it's supposed to (java)?
问题描述
在过去的几个小时中,我尝试用Java编写选择排序算法,而无需查看完成的代码。我刚刚(通过文字)阅读了该算法的工作原理。
In the last hours I have tried to write the selection sort algorithm in Java without looking at finished code. I just read how the algorithm works (by words).
我不会复制粘贴说明,而是进行描述(以检查我是否理解):
I won't copy paste the explanation but rather depict it (to check if I understood it):
-我们有一个未排序的数组A和一个空数组B(其大小与A相同)
-We have one unsorted array A and an empty array B (which has the same size as A)
-现在,请使用未排序的数组A并找到其最小元素。找到的最小元素,现在将其与未排序数组A的第一个元素切换
-Now take the unsorted array A and find its smallest element. Smallest element found, now switch this element with the first element of the unsorted array A
-将第一个元素(=数组A的最小元素)放入数组B
-Put the first element (=smallest element of array A) into the array B
-重复直到完成A的每个元素
-Repeat till we are done with every element of A
我尝试用Java编写代码:
I tried to code that in Java:
public class Selectionsort{
public static void main(String[] args) {
int[] myArray = {9,6,1,3,0,4,2};
int[] B = new int[myArray.length];
for(int i=0; i<myArray.length; i++) {
B[i]=findMIN(myArray, i);
}
}
static int findMIN(int[] A, int c) {
int x = A[c];
while(c<A.length) {
if(x>A[c]) {
x=A[c];
}
c++;
}
return x;
}
}
但是我得到了一个奇怪的输出:
But I get a weird output:
0 0 0 0 0 2 2
推荐答案
首先,修复您的 findMIN
,您应该返回最小值的 index 元素(并将当前值的元素与最小值进行比较)。例如,
First, fix your findMIN
, you should return the index of the minimum element (and compare the element at the current value to the minimum). Like,
static int findMIN(int[] A, int c) {
int x = c;
for (; c < A.length; c++) {
if (A[c] < A[x]) {
x = c;
}
}
return x;
}
然后我将使用交换
方法,例如
Then I would use a swap
method, like
static void swap(int[] A, int a, int b) {
if (a != b) {
int t = A[a];
A[a] = A[b];
A[b] = t;
}
}
最后,将其绑在一起
public static void main(String[] args) {
int[] myArray = { 9, 6, 1, 3, 0, 4, 2 };
for (int i = 0; i < myArray.length; i++) {
swap(myArray, i, findMIN(myArray, i));
}
System.out.println(Arrays.toString(myArray));
}
然后,我得到
[0, 1, 2, 3, 4, 6, 9]
这篇关于为什么我的选择排序算法不执行应有的功能(java)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!