QuickSort Lomuto算法

时间:2018-09-06 18:32:11

标签: javascript quicksort

我正在运行基于https://en.wikipedia.org/wiki/Quicksort

的Lomuto Quicksort算法的实现

要进行测试,我正在尝试几个数组,以查看排序算法是否正确实现。

测试用例:

Array # 1: [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92] 
Array # 2: [11,8,14,3,6,2,7]

根据我对Lomuto算法的理解,这是Wikipedia的代码,其后是tee:

function quickSort(array) {
  // change code below this line
  var n = array.length;
  var low, hii;
  low = 0;
  hii = n - 1;
  // console.log(sub_qs(array, low, hii));
  array = sub_qs(array, low, hii);
  console.log(array);

  /***** Lomuto Algorithm Scheme *****/
  function sub_qs(arr, lo, hi) {
    if (lo < hi) {
      var p = partition(arr, lo, hi);
      sub_qs(arr, lo, p - 1);
      sub_qs(arr, p + 1, hi)
    }
    return arr;
  }

  function partition(a, l, h) {
    var pivot = a[h];
    var i = l;
    for (var j = l; j < h - 1; j++) {
      if (a[j] < pivot) {
        var temp = a[i];
        a[i] = a[j];
        a[j] = temp;
        i++;
      }
      var temp_1 = a[i];
      a[i] = a[h];
      a[h] = temp_1;
    }
    return i;
  }
  /***** Lomuto Algorithm Scheme *****/

  // change code above this line
  return array;
}

运行该程序后,我的结果是:

Results # 1: [1, 1, 8, 2, 32, 2, 63, 43, 55, 43, 123, 4, 92, 345, 123, 234, 5643]
Results # 2: [3, 6, 8, 7, 11, 2, 14]

有些不对劲。我可能做错了什么?

1 个答案:

答案 0 :(得分:0)

在分区中,第二个交换应该在for循环之外,并且for循环需要包含h - 1,因此请使用for (var j = l; j < h; j++)for (var j = l; j <= h -1; j++)

function quickSort(array) {
  // change code below this line
  var n = array.length;
  var low, hii;
  low = 0;
  hii = n - 1;
  array = sub_qs(array, low, hii);

  /***** Lomuto Algorithm Scheme *****/
  function sub_qs(arr, lo, hi) {
    if (lo < hi) {
      var p = partition(arr, lo, hi);
      sub_qs(arr, lo, p - 1);
      sub_qs(arr, p + 1, hi)
    }
    return arr;
  }

  function partition(a, l, h) {
    var pivot = a[h];
    var i = l;
    for (var j = l; j < h; j++) { // << need to be  j < h not h - 1
      if (a[j] < pivot) {
        var temp = a[i];
        a[i] = a[j];
        a[j] = temp;
        i++;
      }
    }
    // this swap should be outside the above for loop <---
    var temp_1 = a[i];
    a[i] = a[h];
    a[h] = temp_1;

    return i;
  }
  /***** Lomuto Algorithm Scheme *****/

  // change code above this line
  return array;
}

let array1 = [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
let array2 = [11, 8, 14, 3, 6, 2, 7]
console.log(quickSort(array1).join(','))
console.log(quickSort(array2).join(','))