如何围绕最小值

时间:2017-02-07 15:54:45

标签: javascript algorithm sorting recursion

我正在尝试使用递归在链表上执行选择排序,并且我在通过递归排序函数在每次传递中使用最小值的节点周围划分链接列表时遇到一些问题。我试图获取具有最小值的节点,围绕最小值对链表进行分区,将最小值附加到前面,加入两个分区列表,然后在加入的分区列表上再次执行排序,直到整个链表排序。例如:

 q w  e  r t // partition around e
 e  -> q w r t // join the partitions
 eq -> w r t // append q to e
 eq -> w r t // partition around r

等等。

我的排序方法:

 Node.prototype.sort = function(){
   if(!next){
      return this;
 } else {
    var a = null;
    var b = null;
    var smallest = this.smallest();
    splitIt(smallest, a, b);
    appendSmallest(smallest);
    a.join(b);
    a.sort();
  }
}

我得到了最小的节点:

 Node.prototype.smallest = function(){
   if(!next) return this;
   var sm = next.smallest();
   if(sm.data < this.data){
      return sm;
   }
   return this;
 }

以下是我的追加和加入方法:

 Node.prototype.appendSmallest = function(smallest){
    if(!next) next = smallest;
 }


 Node.prototype.join = function(otherNode){
     if(!next) next = otherNode;
     else next.join(otherNode);
 }

我在递归地实现splitIt方法时遇到了一些麻烦。伪代码对于这种操作会是什么?

1 个答案:

答案 0 :(得分:1)

我假设您使用的是纯JavaScript,因为没有其他指示。

在您的代码中,您使用单词Node多次作为变量类型,而这种方式是无效的JS。使用单词var声明变量(对于块作用域变量,使用ECMAScript6 let声明)。看看this question。因此,例如在最小的时候你写:

var sm = next.smallest();

sort中,您还有两个问题:首先,您将空变量作为参数传递,希望函数将分配将替换它们的对象(请参阅有关参考值性质的说明here JS中的变量(不是原始值)。第二,假设你忘了但是想在appendSmallest

中加入这一行
else { next.appendSmallest(smallest);}

然后我认为你有一个无限循环,因为smallest附加到这个链表,这是(如果splitIt正常工作)与a相同。

我的建议是进行拆分并作为“spitSmallest”函数连接在一起:

Node.prototype.spitSmallest = function(smallest){
    //we know that this node is not smallest
    if (this.next  == smallest){
        this.next = this.next.next;
        smallest.next = null; //again not really needed
    } else {
        this.next.spitSmallest(smallest);
    }
}

Node.prototype.sort = function(){
   if(!this.next){
      return this;
 } else {
    var smallest = this.smallest();
    var restHead;
    if (smallest==this){
        restHead = this.next;
        this.next = null; //not needed but makes it more readable
    } else {
        restHead = this;
        this.spitSmallest(smallest);
    }
    smallest.next = restHead.sort();
    return smallest;
  }
}
相关问题