Exploring the Big O complexity of QuickSort in JavaScript

My experience with QuickSort involved testing two algorithms on LeetCode for a specific problem. Surprisingly, both algorithms worked, but one outperformed the other significantly, leaving me puzzled about the reason behind the speed difference.

One of the algorithms exceeded the time limit set by LeetCode:

function quickSort(array) {
    quickSortHelper(array, 0, array.length - 1);
    return array;
}

function quickSortHelper(array, start, end) {
    // Handling edge case
    if(start >= end) return;
    // Always selecting the pivot index at the beginning of the array.
    const pivot = start;
    // Placing the left index next to the pivot on the right.
    let left = start + 1;
    let right = end;

    while (right >= left) {
        if (array[left] > array[right] && array[right] < array[pivot])
            swap(left, right, array);
        if (array[left] < array[pivot]) left += 1;
        if (array[right] > array[pivot]) right -= 1;
    }

    swap(pivot, right, array);

    // Always sorting the smaller sub-array first
    const leftIsSmaller = right - 1 - start < end - (right + 1);

    if (leftIsSmaller) {
        quickSort(array, start, right - 1);
        quickSort(array, right + 1, end);
    }
    else {
        quickSort(array, right + 1, end);
        quickSort(array, start, right - 1);
    }
}

function swap(a, b, array) {
    [array[a], array[b]] = [array[b], array[a]];
    return array;
}

Analysing the Big O notation:

  • Worst case: Time = O(n^2) due to repetitive swapping of pivot to the end of the unsorted part, leading to O(n*n) complexity
  • Best case: Time = O(nlog(n)) when the pivot divides the array into two equal halves
  • Average case: Time = O(nlog(n))
  • Space complexity = O(log(n)) because of recursive calls with two sub-arrays and prioritizing quicksort on the smaller sub-array

The other algorithm didn't exceed LeetCode's time limit and surprisingly, it showcased significantly better performance than most submissions. Although having two while loops nested within the main loop, it proved to be more efficient than perceived.

function quickSort(array) {
    sortHelper(array, 0, array.length - 1);
    return array;
}

function sortHelper(array, start, end) {
    if (start >= end) return;
    let i = start;
    let j = end;
    let base = array[i];

    while (i < j) {
        while (i < j && array[j] >= base) j -= 1; // This step makes sense but its timing priority raises questions
        array[i] = array[j]; // Questioning the need for this line
        while (i < j && array[i] <= base) i += 1;
        array[j] = array[i]; // and this line. Aren't these lines risking loss of access to array values?
    }
    array[i] = base;
    sortHelper(array, start, i - 1);
    sortHelper(array, i + 1, end);
}

The disparity in performance between the algorithms leaves me questioning the reasons behind such outcomes.

Answer №1

When comparing the time complexity of two versions, the key difference lies in the number of repeated data comparisons. The first version often ends up re-evaluating the same or opposite data multiple times, which is not the case in the second version.

For instance, if we consider the scenario where the first expression is true and the second false in the following if statement, and this pattern continues over several iterations:

 if (array[left] > array[right] && array[right] < array[pivot])

...it becomes evident that checking the first expression multiple times when it remains true due to the constant value of left is inefficient.

Consider an extreme example array: [1, 6, 3, 2, 5, 4]

The pivot in this case is 1.

Throughout all iterations, the right index decreases until it reaches the left side. In this scenario, the number of comparisons per iteration is 4, making it a total of 20 comparisons over the 5 iterations.

In contrast, the faster algorithm reduces the number of comparisons for the same input to 5 for the first inner loop and 0 for the second inner loop (only counting data comparisons).

While this example demonstrates a significant difference (20 versus 5), similar patterns can be observed with other random inputs to a lesser extent.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty executing the .exec() method of the nodejs simple-ssh module

I am currently using npm's simple-ssh library to establish a connection with a remote host as the root user. I have an additional superuser account named serviceUser. My objective is to switch to this user by running su serviceUser (Note: su service ...

What is the best way to increase incremental values that are nested within each other

A database has been loosely created with a key known as website. Inside this website object, multiple objects exist, one for each dynamically generated website. An illustration of how the database might appear is shown below: website: { google.com: { ...

Troubleshooting a 404 error for an existing object: What to do?

I encounter a 404 'Not Found' error when attempting to edit a mark through my form. I am puzzled by the source of this error because in order to access this form, I require the brand ID (which can be found in the URL). Upon accessing my modifica ...

The AXIOS method in Express.js is designed to return a Promise object that may contain an

I am currently learning ExpressJS and Axios I have created a folder named utils and placed the axios.js file const axios = require('axios'); loadDataPesan=async function(opts){ axios.get('localhost/getData', { params ...

Run the script within the Angular scope

Hey there! I'm having an issue passing a JavaScript code through Angular scope, but when it renders on the view page, it's displayed as text. I even attempted using ng-Sanitize, but unfortunately, that didn't solve the problem. &lt;div ...

What could be preventing this src tag from loading the image?

Here is the file structure of my react project Within navbar.js, I am encountering an issue where the brand image fails to load from the Assets/images directory. import '../../Assets/Css/Navbar.css'; import image from '../../Assets/Images/a ...

What is the process for NPM to execute a command that is not located in the path directory?

When I try to run the ava command from my project directory that contains AVA tests, I encounter an issue because it is not in my path. In my project, the npm test command is configured as ava tests/*.js --verbose, and mysteriously manages to execute the ...

Align the text on the same horizontal line

I have been struggling with this issue for hours. Here is my Header.js <div className="navbar-inner"> <h2>Text1</h2> <h3>Text2</h3> </div> This is the content of my Header.css: .navbar-inner { ...

JavaScript Error: The code is expecting an object when creating a new instance,

Why isn't this code working as expected? var navbar = document.getElementById("navbar").getElementsByTagName("li"); var hover; var moname; var slider; var newPos=new Object(); var body=document.getElementsByTagName('body& ...

What are the differences between jQuery, jQuery Mobile, and jQuery UI?

As someone fresh to web development, I find myself overwhelmed by the numerous frameworks available. I am interested in learning about the distinctions between these frameworks and how they can benefit my projects. Additionally, I am curious as to why jQu ...

Learn how to stream videos using the YouTube Player API's loadPlaylist feature

Is there a way to make the next video play automatically using the loadPlaylist option? I've tried implementing this code but unfortunately, it doesn't work and the video won't play: <div id="player"></div> <script> var ...

Downloading Files through AngularJS on the Front End

When I click the download button next to the file name, I am retrieving the file content from the backend. The content is in bytes and the file can be of any type. How do I convert the data received from the backend into a file and automatically download ...

Using jQuery to Validate Input Text Control Depending on Radio Selection

How can I ensure that the input text linked to the selected radio option is filled in? For instance, in the example above: If Contact 1's Email radio option is chosen, the Email text field for Contact 1 must not be empty, while the Phone and US Mai ...

Ways to extract a string from an array

Currently, I am focusing on programming in C. One of the tasks I am working on involves a function that utilizes getline to receive input from the user. If the first word in a text string is 'S,' it will trigger a function to save a 2D array to ...

How can you eliminate the first elements of two or more arrays of objects until all of their first elements match based on a specific field?

My Typescript code includes a Map object called `stat_map` defined as const stat_map: Map<string, IMonthlyStat[]> = new Map(); The interface IMonthlyStat is structured as shown below (Note that there are more fields in reality) export interface IMon ...

Why isn't my textarea in jQUERY updating as I type?

On my website, I have a comment script that is not functioning correctly in some parts of the jQuery/JavaScript code. Instead of posting an edited comment to PHP, I created a notification window to test if the value passed through is actually changing. W ...

What is the best way to ensure that an ASync function only continues once all necessary information has been collected?

retrieveStudentGrades() { let grades = {}; let totalStudents = this.state.studentDetails.length; let studentCount = 0; this.state.courses.map((course) => { this.state.studentDetails.map((student) => { request.get( ...

Keep track of data with pairings of keys and values

I have a set of data with all values in TEXT format. This data pertains to language files used for multi-language translations. data: { 'MAIN_KEY':{ 'A_UNIQUE_KEY':'data1', 'A_UNIQUE_KEY':'data2', ...

Having difficulty automatically populating a textarea with the chosen option from a datalist

Is there a way to automatically populate the Address field of a client in a textarea based on the input of the client's name in an input field? I have created a 'for loop' to retrieve a datalist of client names. For the address, I retrieved ...

Is it possible to reference a .js file within an HTML file using AngularJS?

Having a slight issue with an email function. I experimented with the 'nodemailer' package and successfully sent an email when coding in a .js file. Upon calling the .js file (node emailfile.js), the email was received as expected (code provided ...