However, it is not possible to do so in JavaScript, as the recursion goes too deep for the language to handle.
然而,在 JavaScript 中这种方式不太可行,因为这个算法的递归深度对它来讲太深了。
具体实现
快排
总体逻辑:
1 2 3 4 5 6 7 8 9 10 11 12 13
functionquickSort(arr, left, right) { var len = arr.length, partitionIndex, left = typeof left != 'number' ? 0 : left, right = typeof right != 'number' ? len - 1 : right;
functionmerge(leftArr, rightArr){ var result = []; while (leftArr.length > 0 && rightArr.length > 0){ if (leftArr[0] < rightArr[0]) result.push(leftArr.shift()); //把最小的最先取出,放到结果集中 else result.push(rightArr.shift()); } return result.concat(leftArr).concat(rightArr); //剩下的就是合并,这样就排好序了 }
functionmergeSort(array){ if (array.length == 1) return array; var middle = Math.floor(array.length / 2); //求出中点 var left = array.slice(0, middle); //分割数组 var right = array.slice(middle); return merge(mergeSort(left), mergeSort(right)); //递归合并与排序 }