<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Abhishek Mittal</title>
    <description>The latest articles on Forem by Abhishek Mittal (@abhishekmittal).</description>
    <link>https://forem.com/abhishekmittal</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F114322%2F735e6c37-8a16-4e58-a859-abce69499520.jpeg</url>
      <title>Forem: Abhishek Mittal</title>
      <link>https://forem.com/abhishekmittal</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/abhishekmittal"/>
    <language>en</language>
    <item>
      <title>Binary Search on Linked List in Javascript.</title>
      <dc:creator>Abhishek Mittal</dc:creator>
      <pubDate>Tue, 13 Nov 2018 10:54:29 +0000</pubDate>
      <link>https://forem.com/abhishekmittal/binary-search-on-linked-list-in-javascript-49jo</link>
      <guid>https://forem.com/abhishekmittal/binary-search-on-linked-list-in-javascript-49jo</guid>
      <description>

&lt;p&gt;Possibilities we get with javascript, algorithms like Binary Search, Heap Sort, BFS, DFS etc been a crucial part of our academia. What if we can achieve the same with javascript.&lt;/p&gt;

&lt;p&gt;Recently I've been studying in depth of JS and the best of javascript, I end up with is implementing all the algorithms with javascript. How helpful will it be if we can work with them in node environment. &lt;/p&gt;

&lt;p&gt;Let's see an example related to how we can implement a simple Binary Search in a singly linked list.&lt;/p&gt;

&lt;p&gt;All we need to do is create a file linkedList.js&lt;/p&gt;

&lt;p&gt;mkdir link-list-bs&lt;br&gt;
cd link-list-bs&lt;br&gt;
touch linkList.js index.js&lt;br&gt;
Inside our linkList.js add the following snippet:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Node {
    constructor(value, next = null) {
        this.value = value;
        this.next = next;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;In above code it seems pretty similar to the struct in C or class in Java or Python, well we do the same here creating a class which creates a single instance of a Node in your linked list, every time we add a new one to it.&lt;/p&gt;

&lt;p&gt;Now Let's add this code to see how we handle our linked list&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// linkedList.js
// ...

module.exports = class LinkedList {
    /**
     *Creates an instance of LinkedList.
     */
    constructor() {
        this.head = null;
        this.tail = null;
        // to make sure of the valuethis.compare = (a, b) =&amp;gt; a === b;
    }

    /**
     * @description add a new node to the linked list
     *
     * @param {*} value
     * @returns
     */
    append(value) {
        const newNode = new Node(value);

        if (!this.head) {
            this.head = newNode;
            this.tail = newNode;
            return this;
        }

        this.tail.next = newNode;
        this.tail = newNode;
        return this;
    }

    /**
     * @description delete a node from the linked list
     *
     * @param {*} value
     * @returns
     */
    delete(value) {
        if (!this.head) {
            return null;
        }

        let deletedNode = null;

        // if the value is in the first nodewhile (this.head &amp;amp;&amp;amp; this.compare(this.head.value, value)) {
            deletedNode = this.head;
            this.head = this.head.next;
        }

        let currentNode = this.head;

        // if current node is not null travel through the linked list// to find the node with the value and replace the next with the current nodeif (currentNode !== null) {while (currentNode.next) {
                if (this.compare(currentNode.next.value, value)) {
                    deletedNode = currentNode.next;
                    currentNode.next = currentNode.next.next;
                } else {
                    currentNode = currentNode.next;
                }
            }
        }

        // two nodes in the list remainsif (this.compare(this.tail.value, value)) {this.tail = currentNode;
        }

        return deletedNode;
    }
};

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;here now we create another class which we export so that we can create an instance for every time we create a new linked list.&lt;/p&gt;

&lt;p&gt;In class LinkedList we have to member functions:&lt;/p&gt;

&lt;p&gt;append(value) : append function create a new node which sets the head for this instance of class and tail points to the last value of the linked list.&lt;br&gt;
delete(value): delete function deletes the node from the linked list.&lt;br&gt;
Let's get back to our index.js&lt;/p&gt;

&lt;p&gt;const LinkList = require('./linkedList');&lt;br&gt;
add the above line to import LinkList into your playground. More lets set up for binary search.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const init = () =&amp;gt; {
    const ll = new LinkList();

    // adding few elements already sorted
    try {
        ll.append(10);
        ll.append(20);
        ll.append(30);
        ll.append(40);
        ll.append(50);
        ll.append(60);
    } catch (error) {
        console.log(error);
    }
};
init();

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Great!, we are all set. Now we have a linked list of these elements. Now if you wanna see what's going on you can have a peek by consoling:&lt;/p&gt;

&lt;p&gt;console.log('My Linked List: ', JSON.stringify(ll));&lt;br&gt;
Now let's write our binary Search Function inside our index.js&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// index.js

const binarySearch = (head, value) =&amp;gt; {
    let start = head;
    let last = null;

    return null;
};
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;well this doesn't seem right, we need to add the real method here&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 *
 * @description Binary Search
 * @param {*} head
 * @param {*} value
 * @returns
 */
const binarySearch = (head, value) =&amp;gt; {
    let start = head;
    let last = null;
    let mid;
    do {
        if (start === last &amp;amp;&amp;amp; last &amp;amp;&amp;amp; last.value != value) return null;
        mid = middle(start, last);

        if (!mid) return null;

        if (mid.value === value) return mid;
        else {
            mid.value &amp;lt; value ? (start = mid.next) : (last = mid);
        }
    } while (last != null || last === start);

    return null;
};
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now our binarySearch function looks like this. But it won't work until the mid value lets add that :&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 *
 * @description Middle Function
 * @param {*} start
 * @param {*} last
 * @returns
 */
const middle = (start, last) =&amp;gt; {
    if (start === null) {
        return null;
    }

    let slow = start;
    let fast = start.next;

    while (fast != last) {

        fast = fast.next;
        if (fast != last) {
            slow = slow.next;
            fast = fast.next;
        }
    }

    return slow;
};
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;here we are finding the middle node and that's what helps us find out the value lastly.&lt;/p&gt;

&lt;p&gt;All Set, just a final addition to our init function:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// find the value 10 in the linked list
console.log('LL: ', binarySearch(ll.head, 10) ? 'found' : 'does not exist');
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;now, let's run this.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node index.js
// output 
LL:  found
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;So we see, javascript can be used anywhere.&lt;/p&gt;

&lt;p&gt;Try other things with js.&lt;/p&gt;


</description>
      <category>javascript</category>
      <category>data</category>
      <category>structures</category>
      <category>tech</category>
    </item>
  </channel>
</rss>
