在过去的几个小时里,我尝试用 Java 编写选择排序算法,而无需查看已完成的代码。我刚刚阅读了算法的工作原理(通过文字)。
我不会复制粘贴解释,而是描述它(检查我是否理解它):
- 我们有一个未排序的数组 A 和一个空数组 B(与 A 的大小相同)
- 现在取未排序的数组 A 并找到它的最小元素。找到最小的元素,现在将此元素与未排序数组 A 的第一个元素切换
-将第一个元素(=数组A的最小元素)放入数组B
-重复直到我们完成 A 的每个元素
我试图用 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;
}
}
但我得到一个奇怪的输出:
0 0 0 0 0 2 2
首先,修复您的findMIN
,您应该返回最小元素的索引(并将当前值的元素与最小值进行比较)。喜欢,
static int findMIN(int[] A, int c) {
int x = c;
for (; c < A.length; c++) {
if (A[c] < A[x]) {
x = c;
}
}
return x;
}
然后我会使用一种swap
方法,比如
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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句