js快速排序算法

    // 快速排序算法:关键在于定义基准元素,头尾元素与基准元素对比,定义头尾元素下标,头小右移,头大停止,尾大左移,尾小停止,头大尾小元素交换
    function partition(arr, startIndex, endIndex) {
        var pivot = arr[startIndex];
        var left = startIndex;
        var right = endIndex;

        while (left != right) {
            while (left < right && arr[right] > pivot) {
                right--;
            }

            while (left < right && arr[left] <= pivot) {
                left++;
            }
            if (left < right) {
                var temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
            }
        }

        arr[startIndex] = arr[left];
        arr[left] = pivot;
        return left;
    }

    function quickSort(arr, startIndex, endIndex) {
        if (startIndex >= endIndex) {
            return;
        }

        var pivotIndex = partition(arr, startIndex, endIndex);
        quickSort(arr, startIndex, pivotIndex - 1);
        quickSort(arr, pivotIndex + 1, endIndex);
    }

    var Array = [4, 4, 6, 5, 3, 2, 8, 1];
    quickSort(Array, 0, Array.length - 1);
    console.log(Array.join(','));

  

posted @ 2020-03-23 08:52  Peter_Yang0942  阅读(143)  评论(0编辑  收藏  举报