为什么我的选择排序算法不起作用?

时间:2017-10-24 23:15:58

标签: 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[] 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;
  }

当我输入类似的东西时:

  public static void main(String[] args){
    int a[] = {1,-24,4,-4,6,3};
    System.out.println(Arrays.toString(selectionSort(a)));
  }

我得到:     [-24,-24,-4,0,0,0]

哪里出错了?这是一个糟糕的算法吗?

1 个答案:

答案 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;
        }
    }
}

总结

  • 您不需要额外的空间来进行选择排序
  • 交换元素,否则会丢失它们
  • 记住循环不变量很有帮助