快速排序算法中的If/else(js)

问题描述 投票:0回答:1

我目前正在学习一些排序算法,并且实现了快速排序,但是它不能正常工作。它不只是对数组进行排序,而是删除了重复的值。这是我的代码:

function quickSort(array) {
    if (array.length <= 1) return array;

    let pivotIndex = Math.floor(array.length / 2);
    let pivot = array[pivotIndex];
    let less = [];
    let greater = [];

    for (let i = 0; i < array.length; i++) {
        count++;
        if (i === pivotIndex) continue;
        if (array[i] < pivot) { // *
            less.push(array[i]);
        } 
        if (array[i] > pivot) {
            greater.push(array[i])
        }
        
    }

    return [...quickSort(less), pivot, ...quickSort(greater)];
}

当我将两个 if(从 * 行开始)替换为以下代码时,它开始工作:

if (array[i] < pivot) {
   less.push(array[i]);
} else {
   greater.push(array[i])
}

我只是不明白有什么区别以及为什么第一个变体不起作用? 以及为什么它比选择排序甚至有时甚至是冒泡排序的工作时间更长?

我也尝试在每个 if 的末尾添加“继续”,但这没有帮助。

javascript arrays sorting quicksort
1个回答
0
投票

更换:

    if (array[i] < pivot) { // *
        less.push(array[i]);
    } 
    if (array[i] > pivot) {
        greater.push(array[i])
    }

与:

    if (array[i] < pivot) { // *
        less.push(array[i]);
    } else {
        greater.push(array[i])
    }
© www.soinside.com 2019 - 2024. All rights reserved.