【问题标题】:Selection Sort giving the incorrect output选择排序给出不正确的输出
【发布时间】:2013-09-19 06:06:45
【问题描述】:

我在此选择排序中的输出有问题。

代码如下:

public class SelectionSort{
    public static void main(String args[]){

        int [] arr_sort = {1, 7, 2, 18, 23, 13};

        System.out.println("Selection Sort");
        System.out.print("Before sorting: ");
        int x;
        for(x=0; x<arr_sort.length; x++){
            System.out.print(arr_sort[x] + " ");
        }

        System.out.println("");
        System.out.print("After sorting: ");

        int n = arr_sort.length;
        int i,j, min, temp;
        for(i=0; i<n; i++){
            min=1;
        for(j=i+1; j<n; j++){
         if (arr_sort[j]<arr_sort[min]){
            min=j;
            temp=arr_sort[i];
            arr_sort[i]=arr_sort[min];
            arr_sort[min]=temp;
        }

    }

System.out.print(arr_sort[i] + " ");
 }

}

}

输出:

Selection Sort
Before sorting: 1 7 2 18 23 13 
After sorting: 2 1 7 18 23 13 

【问题讨论】:

  • 那么...有什么问题?在阅读您的问题时,我一定错过了那部分。
  • 排序有点乱,你可以在“排序后”看到它应该是:1、2、7、13、18、23。

标签: java selection-sort


【解决方案1】:

min 在循环外声明的事实是问题所在。

开始新的迭代时,它仍会保留旧值,因此您将与已发现最小值并被选中的元素进行比较。

另外,min 不应该是 1,而是改为 i,因为您不想在每一步都与第二个元素进行比较。

在这些更改之后它可以工作,但它不是真正的选择排序,您需要找到最小值然后才交换,而不是每次找到较小的元素时。

进入代码:

int n = arr_sort.length;
int i, j, temp; // min removed here
for (i = 0; i < n; i++)
{
  int min = i; // min declared here and changed to i
  for (j = i + 1; j < n; j++)
  {
     if (arr_sort[j] < arr_sort[min])
     {
        min = j;
     }
  }
  // moved swap to here
  temp = arr_sort[i];
  arr_sort[i] = arr_sort[min];
  arr_sort[min] = temp;
  System.out.print(arr_sort[i] + " ");
}

【讨论】:

  • 我一直试图找出导致此代码问题的原因。你帮了我很多,非常感谢!
猜你喜欢
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-24
  • 2016-07-22
  • 2022-06-10
  • 2018-12-06
  • 1970-01-01
相关资源
最近更新 更多