2014-10-02 139 views
0

希望能够在Javascript中使用此Quicksort算法获得一些帮助(这不是用于作业或任何事情,只是很有趣) - 它不起作用,我不确定哪里出错。JavaScript中的快速排序错误

function quicksort (arr) { 
     // Launch the sorting process. 
     sort(arr, 0, arr.length - 1); 

     /** 
     * swap 
     * takes in an array and two indexes, 
     * swaps the elements in the array at those indexes 
     */ 
     function swap (arr, a, b) { 
      var temp = arr[a]; 
      arr[a] = arr[b]; 
      arr[b] = temp; 
     } 

     function partition (arr, l, r) { 
      var p = arr[r], 
       i = l - 1, 
       j = l; 
      while (j < r - 1) { 
       if (arr[j] <= p) { 
        swap (arr, ++i, j); 
       } 
       j++; 
      } 

      swap (arr, i + 1, r); 
      return i + 1; 
     } 

     function sort (arr, l, r) { 
      var p; 
      if (l < r) { 
       p = partition(arr, l, r); 
       sort(arr, l, p - 1); 
       sort(arr, p + 1, r); 
      } else { 
       console.log(arr);  
      } 
     } 
    } 
+0

你的代码不工作的方式是什么? – APerson 2014-10-02 15:46:24

+0

我给它快速排序([8,3,2,1,5,1,3]) ,它返回:[1,3,2,3,5,8,1] – graemeboy 2014-10-02 15:47:00

+0

对不起,按下输入没有班次和触发了一个不成熟的帖子 – graemeboy 2014-10-02 15:47:59

回答

1

好吧,我想我找到了。这个问题就像我的分区循环一样,我过早地结束了它。下面是完整的代码:

function quicksort (arr) { 
     // Launch the sorting process. 
     sort(arr, 0, arr.length - 1); 

     /** 
     * swap 
     * takes in an array and two indicies, 
     * swaps the elements in the array at those indicies 
     */ 
     function swap (arr, a, b) { 
      var temp = arr[a]; 
      arr[a] = arr[b]; 
      arr[b] = temp; 
     } 

     function partition (arr, l, r) { 
      var p = arr[r], 
       i = l - 1, 
       j = l; 
      while (j < r) { 
       if (arr[j] <= p) { 
        swap (arr, ++i, j); 
       } 
       j++; 
      } 
      // Put the pivot in its correct place 
      swap (arr, i + 1, r); 
      return i + 1; 
     } 

     function sort (arr, l, r) { 
      var p; 
      if (l < r) { 
       p = partition(arr, l, r); 
       sort(arr, l, p - 1); 
       sort(arr, p + 1, r); 
      } else if (l === arr.length) { 
       // Output the sorted array. 
       console.log(arr);  
      } 
     } 
    } 

基本试验:

快速排序([19,12,1,2,3,123,23,2,5]) [1,2,2,3, 5,12,19,23,123]

快速排序([8,3,2,1,5,1,3]) [1,1,2,3,3,5,8]

对如何改进建议开放! :)

+1

+1非常有趣的分区:比通常的左右边界方法更紧凑一点,我今天学到了一些东西:D – BeyelerStudios 2014-10-02 16:26:19