快速 排序 javascript實現

 //快速排序
        function QSort(L, low, high) {
            var pivot;
                while(low<high)
                {
                    pivot = Partition(L, low, high);//將L一分爲二
                    QSort(L, low, pivot - 1);
                    low = pivot + 1;//採用迭代而不是遞歸的方法縮減堆棧深度,從而提升總體性能!
                }
        }
        function swap(L, l, h) {
            var temp = L[h];
            L[h] = L[l];
            L[l] = temp;
        }
        function Partition(L, low, high) {
            //三數取中優化算法 防止最小值過大或者太小
            var pivotkey,temp;
            var m = low + (high - low) / 2;
            m = Math.floor(m);
            if (L[low] > L[high]) {
                swap(L, low, high);
            }
            if (L[m] > L[high])
                swap(L, m, high);
            if (L[m]>L[low])
                swap(L, low, m);
            pivotkey = L[low];
            temp = pivotkey;
            while (low < high) {
                while (low<high&&L[high]>=pivotkey) {//找到比pivotkey小的值的下標,而後把當前值賦值給L[low]
                    high--;
                }
                L[low] = L[high];
                while (low<high&&L[low]<=pivotkey) {
                    low++;
                }
                L[high] = L[low];
            }
            L[low] = temp;
            return low;
        }

        var a = [1, 4, 2, 5, 7, 8, 9, 0, 3, 2];
            //MereSort(l);
        //MergeSort2(l);
        QSort(a, 0, a.length - 1);
        console.log(a);
相關文章
相關標籤/搜索