Java 为什么我的选择排序算法不起作用?
我正在尝试用java制作一个选择排序算法,该算法找到未排序数组的最小元素,并将其放在新数组的末尾。但是我的程序只复制了第一个元素两次,得到了下一个元素,其余的都是零:Java 为什么我的选择排序算法不起作用?,java,algorithm,selection-sort,Java,Algorithm,Selection Sort,我正在尝试用java制作一个选择排序算法,该算法找到未排序数组的最小元素,并将其放在新数组的末尾。但是我的程序只复制了第一个元素两次,得到了下一个元素,其余的都是零: public static int find_min(int[] a){ int m = a[0]; for (int i = 0; i < a.length; i++){ if (m > a[i]) m = a[i]; } return m; }
public static int find_min(int[] a){
int m = a[0];
for (int i = 0; i < a.length; i++){
if (m > a[i])
m = a[i];
}
return m;
}
public static int[] selectionSort(int[] unsorted){
int[] c = new int[unsorted.length];
for(int i = 0; i < unsorted.length; i++){
int smallest = find_min(unsorted);
c[i] = smallest;
unsorted = Arrays.copyOfRange(unsorted, i+1, unsorted.length );
}
return c;
}
我得到:
[24,-24,-4,0,0,0]
哪里出了问题?这是一个糟糕的算法吗?好的,让我们重新讨论选择排序算法
public static void selectionSort(int[] a) {
final int n = a.length; // to save some typing.
for (int i = 0; i < n - 1; i++) {
// i is the position where the next smallest element should go.
// Everything before i is sorted, and smaller than any element in a[i:n).
// Now you find the smallest element in subarray a[i:n).
// Actually, you need the index
// of that element, because you will swap it with a[i] later.
// Otherwise we lose a[i], which is bad.
int m = i;
for (int j = m + 1; j < n; j++) {
if (a[j] < a[m]) m = j;
}
if (m != i) {
// Only swap if a[i] is not already the smallest.
int t = a[i];
a[i] = a[m];
a[m] = t;
}
}
}
publicstaticvoidselectionsort(int[]a){
final int n=a.length;//保存一些输入。
对于(int i=0;i
总之
- 您不需要额外的空间来进行选择排序
- 交换元素,否则将丢失它们
- 记住循环不变量是有帮助的
这是一个糟糕的算法吗?
这是一个糟糕的实现。我给你一个提示。你不必使用数组。copyOfRange
,你也不需要分配一个新数组。如果你使用这些,你的算法就不再是选择排序了。这是很多只选择子数组中最小元素的代码。祝贺你。lilezek,为什么不是选择排序?我以为选择排序是找到未排序数组的最小值并将其放在适当的位置。我应该用什么来代替呢?你有没有费心去看选择排序是如何工作的?例如,看。谢谢!我该如何使用copyOfRange方法?你不需要它。即使你正在使用另一个a为了存储结果,不需要复制原始数组或其任何部分。
public static void selectionSort(int[] a) {
final int n = a.length; // to save some typing.
for (int i = 0; i < n - 1; i++) {
// i is the position where the next smallest element should go.
// Everything before i is sorted, and smaller than any element in a[i:n).
// Now you find the smallest element in subarray a[i:n).
// Actually, you need the index
// of that element, because you will swap it with a[i] later.
// Otherwise we lose a[i], which is bad.
int m = i;
for (int j = m + 1; j < n; j++) {
if (a[j] < a[m]) m = j;
}
if (m != i) {
// Only swap if a[i] is not already the smallest.
int t = a[i];
a[i] = a[m];
a[m] = t;
}
}
}