【问题标题】:Will this code be considered bubble or selection sort?这段代码会被认为是冒泡排序还是选择排序?
【发布时间】:2021-08-17 09:19:18
【问题描述】:

您能帮忙确定这是什么排序方法吗?

public static int[] sort(int arr[]) {
    int temp1 = 0;
    for (int i = 0; i < arr.length; i++) {
        System.out.println(Arrays.toString(arr));
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[j] < arr[i]) {
                temp1 = arr[i];
                arr[i] = arr[j];
                arr[j] = temp1;
            }
        }
    }
    return arr;
}

【问题讨论】:

    标签: java arrays bubble-sort selection-sort


    【解决方案1】:

    两者都没有。它接近选择排序,但会进行不必要的交换。

    冒泡排序对后续元素进行成对交换,直到“最轻”的元素位于顶部,就像气泡在流体中上升一样。

    int unorderedLen = arr.length;
    do {
      int newUnorderedLen = 0;
      // after a cycle, largest element will be at top
      for (int i = 1; i < unorderedLen; j++) {
        if (arr[i-1] > arr[i]) {
          newUnorderedLen = i;
          swap(arr, i, i-1);
        }
      }
      unorderedLen = newUnorderedLen;
    } while (unorderedLen > 0);
    

    选择排序搜索并选择元素应该适合的位置并在之后进行单次交换。

    // at i. cycle, we select i. least element and place at i.
    for (int i = 0; i < arr.length-1; i++) {
      int minIndex = i;
      // search for least element in the remaining unsorted
      for (int j = i+1; j < arr.length; j++) {
        if (arr[j] < arr[minIndex]) {
          minIndex = j;
        }
      }
      if (minIndex != i) {
        swap(arr, minIndex, i);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 2011-08-02
      • 2015-09-12
      • 2015-02-14
      相关资源
      最近更新 更多