使用大写和小写字母为特定情况排序比较器

时间:2017-08-07 08:51:53

标签: javascript algorithm sorting mergesort

我有一个像这样的合并排序脚本:

function mergeSort(arr){
   var len = arr.length;
   if(len <2)
      return arr;
   var mid = Math.floor(len/2),
       left = arr.slice(0,mid),
       right =arr.slice(mid);
   //send left and right to the mergeSort to broke it down into pieces
   //then merge those
   return merge(mergeSort(left),mergeSort(right));
}


function merge(left, right){
  var result = [],
      lLen = left.length,
      rLen = right.length,
      l = 0,
      r = 0;
  while(l < lLen && r < rLen){
     if(left[l] < right[r]){
       result.push(left[l++]);
     }
     else{
       result.push(right[r++]);
    }
  }  
  //remaining part needs to be addred to the result
  return result.concat(left.slice(l)).concat(right.slice(r));
}

console.log(mergeSort(['a', 'B', 'b', 'A', 'c']))

输出是:

["A", "B", "a", "b", "c"]

我希望订购

["A", "a", "B", "b", "c"]

toLowerCase()方法不起作用,因为它可以返回如下内容:

["A", "a", "b", "B", "c"]

此致

2 个答案:

答案 0 :(得分:2)

基本上你可以先比较小写字符,如果相等,则反转String#localeCompare的结果。

&#13;
&#13;
var array = ['a', 'B', 'b', 'A', 'c'];

array.sort(function (a, b) {
    var aa = a.toLowerCase(),
        bb = b.toLowerCase();

    return aa.localeCompare(bb) || b.localeCompare(a);
});

console.log(array);
&#13;
&#13;
&#13;

使用您的代码

&#13;
&#13;
function compare(a, b) {
    var aa = a.toLowerCase(),
        bb = b.toLowerCase();

    return aa.localeCompare(bb) || b.localeCompare(a);
}

function mergeSort(arr) {
    var len = arr.length;
    if (len < 2) {
        return arr;
    }
    var mid = Math.floor(len / 2),
        left = arr.slice(0, mid),
        right = arr.slice(mid);
    //send left and right to the mergeSort to broke it down into pieces
    //then merge those
    return merge(mergeSort(left), mergeSort(right));
}

function merge(left, right) {
    var result = [],
        lLen = left.length,
        rLen = right.length,
        l = 0,
        r = 0;
    while (l < lLen && r < rLen) {
        if (compare(left[l], right[r]) < 0) { // use comparing function and check
            result.push(left[l++]);           // against zero for smaller values
        } else {
            result.push(right[r++]);
        }
    }
    //remaining part needs to be addred to the result
    return result.concat(left.slice(l)).concat(right.slice(r));
}

console.log(mergeSort(['a', 'B', 'b', 'A', 'c']))
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您需要做的就是改变行中的if语句

if(left[l] < right[r])

用于检查小写字符和小写字符相等的情况

if( left[l].toLowerCase() < right[r].toLowerCase() || (left[l].toLowerCase() == right[r].toLowerCase() && left[l] < right[r]) ) 最好的问候