DEV Community

Cover image for Algorithms in JavaScript with visual examples.

Algorithms in JavaScript with visual examples.

Swastik Yadav on November 30, 2021

Hello Programmers, Most of us are scared of algorithms, and don't ever start to learn it. But we shouldn't be scared of it. An algorithm is just s...
Collapse
 
jeffchavez_dev profile image
Jeff Chavez

Wow. I'll learn this.

Collapse
 
swastikyadav profile image
Swastik Yadav

Glad that you liked it.

Collapse
 
sanzhardanybayev profile image
Sanzhar Danybayev

You have an error in LSP value. It must be [0, 0, 0, 3, 5, 0] instead of [0, 0, 0, 1, 2, 0]

Collapse
 
sanzhardanybayev profile image
Sanzhar Danybayev • Edited

You actually have a wrong LPS algorithm. Here's the right one:

function calculateLpsTable(subStr) {
    let i = 1;
    let j = 0;
    let lps = new Array(subStr.length).fill(0);

    while(i < subStr.length) {
        if(subStr[i] === subStr[j]) {
            lps[i] = j + 1;
            i += 1;
            j += 1;
        } else {
            if(j !== 0) {
                j = lps[j - 1];
            } else {
                i += 1;
            }
        }
    }
    return lps;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
swastikyadav profile image
Swastik Yadav

There was a small typo at line 8. Wrote "i" instead of "1".

Thanks for pointing.

Collapse
 
swastikyadav profile image
Swastik Yadav • Edited

LPS value is actually correct. It is [0, 0, 0, 1, 2, 0]

I had a small typo in LPS algorithm. I added "i" instead of "1".

Thanks for pointing.

Collapse
 
sanzhardanybayev profile image
Sanzhar Danybayev

Yeah, that all because of the type. It changed the value and it also causes infinite loop.
Nevertheless that was a pleasure to read your article!

Collapse
 
jeevikasirwani profile image
jeevikasirwani

Hey please can you tell me which website did you use to add those code snippets?

Collapse
 
swastikyadav profile image
Swastik Yadav

Those code snippets are not added via any website. I wrote the article in markdown along with the code, and the snippets' design is native to dev.to platform itself.

Collapse
 
ggenellina profile image
Gabriel Genellina

You got the O(n^2) complexity wrong. O(n^2) is quadratic complexity, a special case of polynomial complexity O(n^k).
Exponential complexity is O(2^n) and none of your example algorithms have exponential complexity.

Collapse
 
swastikyadav profile image
Swastik Yadav

Yes, you are right. Thaks for this. I will fix it soon.

Collapse
 
slidenerd profile image
slidenerd

wouldnt life be amazing if everything was O(1)

Collapse
 
lazareric profile image
Lazar Eric • Edited

Wonderful post, thank you.

Radix sort improvement to handle negative integers, in my own writing:

// Including the sign (+,-) 
function maxDigits(array) {
    return Math.max(...array.map(item => String(item).length));
}

function getDigit(value, i) {
    let response = String(value);

    const index = response.length - 1 - i;

    response = index >= 0 ? response[index] : undefined;

    return ['+', '-'].includes(response) ? -1 : !response ? 0 : +response;
}

function radixSort(value) {
    let array = value;
    const digits = maxDigits(array);

    // Digits 
    for (let i = 0; i < digits; i++) {
        // sign, and 10 number digits 0-9, 11 
        const buckets = Array.from({ length: 11 }, () => []);

        // Array 
        for (let j = 0; j < array.length; j++) {
            // -1 for sign, 0 for 0 or no value, and 0-9 for a value 
            const index = getDigit(array[j], i);

            buckets[index + 1].push(array[j]);
        }

        array = buckets.flatMap(item => item);
    }

    return array;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stonito69 profile image
Toni Stojev

In binary search, you have an infinite loop for non-existent member search.
Correct while loop exit term should be:

  while (array[middleIndex] !== element && firstIndex !== middleIndex && middleIndex!==firstIndex)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
amirkhansinga profile image
amirkhansinga • Edited

Very well explain Appreciated your efforts... Really Nice.

Website

Collapse
 
brunopanassi profile image
Bruno Panassi

This is gold, thank you for sharing this!

Collapse
 
swastikyadav profile image
Swastik Yadav

Thank you Bruno. 🙏

I am glad that you found this useful. 😊

Collapse
 
alexiades profile image
Alejandro Alexiades

Very nice article, thanks

Collapse
 
swastikyadav profile image
Swastik Yadav

Thanks for your kind words Alejandro. It means a lot. 😊

Collapse
 
bensembira1 profile image
Ben Sembira • Edited

Isn’t it a bit cheating to say that in the radix sort algorithm k x m = n?

I mean, it is true but if the largest number in the array is at least propotional to the size of the array (which is very likely) then k becomes Ω(log m) (lower bound) and in this case for being more fair with the other algorithms, if we define n to be the length of the array we will get something close to O(n log n).

Just putting it here for those who would confuse and think that radix sort is absolutely better then quick sort or merge sort. It depends on the data and the free space you have.

  • Quick sort is an in place sorting algorithm while radix uses additional O(m) space.
  • Sorting one million people by their age (as an int) is a classic radix sort example because of the small range numbers can be in, but sorting one million people by the amount of money they have in their bank account will probably do better with quick sort.
Collapse
 
andrewbaisden profile image
Andrew Baisden

Super post! So much great content shared here. Algorithms are such a pain to learn and really hold some developers back from applying for jobs.

Collapse
 
swastikyadav profile image
Swastik Yadav

Thank you Andrew. 😊

This motivates me to write more.

Collapse
 
fridaycandours profile image
Friday candour

Hmm, you just let me know I don't have to buy a course to learn algorithms, I love your content, eyes on you bro, thanks for making me happy.

Collapse
 
swastikyadav profile image
Swastik Yadav

This is the best comment I have ever got.

Thanks for being so kind, brother. 🙏

You literally made my day. 😊

Collapse
 
amrelmohamady profile image
Amr Elmohamady

Have you thought about making a website with algorithms explained in javascript?

Collapse
 
swastikyadav profile image
Swastik Yadav

Hey Amr,

Thank you so much for your interest. I haven't thought about it, but it seems to be a really great idea.

I will definitely think about it. Thank you for the suggestion man.

Collapse
 
eteimz profile image
Youdiowei Eteimorde

Awesome one.

Collapse
 
swastikyadav profile image
Swastik Yadav

Thank You, Youdiowei.

This really means a lot.

Collapse
 
brinthsanti profile image
Brinth Santi

This is great 👌

Collapse
 
swastikyadav profile image
Swastik Yadav

Thank You for the kind words Brinth.

Collapse
 
swastikyadav profile image
Swastik Yadav

Thanks a lot decker.

Collapse
 
harsh29 profile image
Harsh Trivedi

Hey Swastik,
Awesome article, any chance you can share how you created the visuals for the tutorial. TIA

Collapse
 
heferh24 profile image
HeferH24

shouldn't KMP algorithm return the index?

Collapse
 
johnkey profile image
INDERA SHAH • Edited

cryto