【发布时间】:2018-09-30 00:19:05
【问题描述】:
/* 这是提示:
以未排序的数组 a 开始
输出:排序后的数组 a。
在数组a[1:n]中找到最小的元素,称它为a[j]。 如果它小于 a[0],则将其与 a[0] 交换。 对索引 1、2、... 重复此过程,直到对 who 数组进行排序。 */
public class assing2 {
public static void main(String args[])
{
//array of ints
int[] A = new int[] {33, 20, 8, 11, 5};
int min_id = 0;
int temp_i = 0;
//int temp_max = 0;
for (int i = 0; i < A.length; i++)
{
min_id = i;
temp_i = A[i];
for (int j = 1; j < A.length; j++)
{
if (A[min_id] > A[j])
{
min_id = j;
}
}
A[i] = A[min_id];
A[min_id] = temp_i;
}
System.out.println("Sorted array");
for ( int i = 0; i < A.length; i++)
{
System.out.println(A[i]);
}
}
}
这是输出
排序数组
5
20
11
33
8
当我在调试器中运行它时,我可以看到第一个 for 循环的前 2 次迭代看起来像是在工作,但之后它对已排序的内容进行了排序。
我的逻辑有什么问题?
【问题讨论】:
-
阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 了解如何调试代码的提示。