简体   繁体   中英

Why quick sort is always slower than bubble sort in my case?

They use same array:

QUICK SORT Time: 3159 miliseconds (array length 10K)

Bubble SORT Time: 1373 miliseconds (array length 10K)

I'm trying to compare time of the sorting using quick and bubble sort algoritms. I use the array with 10K different random numbers sorted in random order for both functions. But for some reason bubble sort is always sort array faster than quick sort, even if average time complexity of bubble sort is worse than average time complexity of quick sort. Why bubble sort algorithms slower than quick sort algorithm in my case? (I tried different lengths of array, from 10 to 10K)

Thats my quick sort function

let quickSort = (arr) => {
    if (arr.length <= 1) {
        return arr
    }
    const pivot = arr[0]
    const rest = arr.slice(1);
    let left = [],
        right = [];
    rest.forEach(el => el > pivot ? right = [...right, el] : left = [...left, el]);
    return [...quickSort(left), pivot, ...quickSort(right)];
}

And that's my bubble sort function

let bubbleSort = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        for (let s = i + 1; s < arr.length; s++) {
            if (arr[s] < arr[i]) {
                let a = arr[i];
                arr[i] = arr[s]
                arr[s] = a;
            }       
        }
    }
    return arr
}

Just as @Barmar said, Quicksort is making a lot of copies.

Also, each spread operator (the 3 dots operator) has a complexity of O(n) as it iterates through the whole array (like a simple for loop) which might also makes the algorithm slower.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM