Month: December 2020

  • Binary Search algorithm

    Binary Search algorithm

    Basics

    The main requirement for the binary search is: Array must be sorted.

    The binary search work in the same way as searching phone number by person name in phonebook.

    Or similar to searching word in the dictionary.

    For example you need to find word “Mars”. What the steps people usually do:

    1. Open the dictionary in the middle and check any word
    2. If the word started from “P” then the word “Mars” located in the first part of the book.
    3. Then you divide the first part of the book and check the next word.
    4. The next word can start from “G”.
    5. In this case we need search second part of the first part of the book.

    So, the range for the search becomes 2 times less every step.

    The algorithm time complexity is O(log n)

    See the illustration below:

    Video with binary search in action

    Diagrams

    Loop implementation

    PlantUML Syntax:<br /> @startuml</p><p>skinparam padding 10</p><p>start</p><p> repeat</p><p> :Found element between start and finish index. Middle element;</p><p> if (“Middle element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return middle element index;<br /> stop<br /> elseif (“Start element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return start element index;<br /> stop<br /> elseif (“Finish element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return finish element index;<br /> stop<br /> elseif (“Middle element<br /> bigger than<br /> needed element?”) then (yes)<br /> :Finish index = Middle index – 1;<br /> elseif (“Middle element<br /> less than<br /> needed element?”) then (yes)<br /> :Start index = Middle index + 1;<br /> endif</p><p> repeat while (startIndex less than finishIndex) is (no)</p><p> :Search finished;<br /> :Return no item found result;</p><p>stop</p><p>@enduml<br /> ” usemap=”#plantuml_map”></p><h3 class=Recursively implementation

    PlantUML Syntax:<br /> @startuml</p><p>skinparam padding 10</p><p>start</p><p>:Found element between start and finish index. Middle element;</p><p>if (“Middle element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return middle element index;<br /> stop<br /> elseif (“Start element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return start element index;<br /> stop<br /> elseif (“Finish element<br /> equals to<br /> needed element?”) then (yes)<br /> :Search finished;<br /> :Return finish element index;<br /> stop<br /> elseif (“Middle element<br /> bigger than<br /> needed element?”) then (yes)<br /> :Recursion.<br /> Start search from start index<br /> to (middle element – 1);<br /> stop<br /> elseif (“Middle element<br /> less than<br /> needed element?”) then (yes)<br /> :Recursion.<br /> Start search from (middle element + 1)<br /> to finish Index;<br /> stop<br /> else<br /> :Search finished;<br /> :Element not found;<br /> stop<br /> endif<br /> @enduml<br /> ” usemap=”#plantuml_map”></p><h2 class=Sample code

    Below you will get a link to GitHub repo with Kotlin, Java, and Python source code

    Download it from github
  • Reverse a Linked List in groups of a given size

    Reverse a Linked List in groups of a given size

    Basics

    In the previous post, we talked about reverse the entire LinkedList. You also can get info about what is it LinkedList and a high-level view of how it works.

    Here is the link: https://www.hrupin.com/2020/12/reverse-a-linked-list-in-groups-of-given-size-algorithm

    Today we will talk about a case when we need to revert linked list nodes in groups of a given size.

    Algorithm theory

    Task definition

    Given LinkedList:
    5–>8–>13–>56–>12–>90–>53–>23–12–>NULL
    Given group size: 3
    We need split linked list into groups and reverse the nodes.
    The result linked list must be like this:
    13–>8–>5–>90–>12–>56–>12–>23–53–>NULL

    Solution

    1. Reverse the first sub-list of size k. While reversing keep track of the next node and previous node. Let the pointer to the next node be next and the pointer to the previous node be prev. See this post for reversing a linked list.
    2. head->next = reverse(next, k) ( Recursively call for rest of the list and link the two sub-lists )
    3. Return prev. Prev becomes the new head of the list

    Sample code

    Below you will get a link to GitHub repo with Kotlin, Java, and Python source code

    Download it from github

  • Reverse a linked list algorithm

    Reverse a linked list algorithm

    Basics

    Linked list is a data structure each element of those has link to the next element.

    Each element of the linked list called node

    The node of linked list called head. To identify the whole linked list we need link to head only.

    The linked lists are great in insertion and deleting first and last elements. They can used for implementing stacks, queues.

    Time and complexity for LinkedList

    OperationComplexity explanationComplexity formula
    InsertionconstantO(1)
    DeletionconstantO(1)
    SearchlinearO(n)
    SpacelinearO(n)

    Algorithm theory

    Task definition

    We have a linked list.

    We need reverse items in the existing linked list.

    Solution

    The simplest way to solve the task is to iterate through the list and set the previous node as the next node for each node. The next node for the first node must be null.

    The complexity in this case will be 0(n).

    Diagram

    PlantUML Syntax:<br /> @startuml</p><p>start</p><p> repeat</p><p> if (“Is Head Node?”) then (yes)<br /> :Set next node as NULL;<br /> else (no)<br /> :Set next node as previous;<br /> endif<br /> :Save current node in previous field;</p><p> repeat while (Next node is NULL) is (no)</p><p> :Save the previous field as head;</p><p>stop</p><p>@enduml<br /> ” usemap=”#plantuml_map”></p><h2 class=Sample code

    Below you will get a link to GitHub repo with Kotlin, Java, and Python source code

    Download it from github
  • Dijkstra algorithm

    Dijkstra algorithm

    Algorithm for finding the shortest path from one vertex of the graph to all the others.

    This algorithm was developed by the Dutch scientist Edsger Wybe Dijkstra in 1959.

    The algorithm works only for a directed graph in which the edges have no negative weight and do not have loops. Or is works only with DAG (Directed Acyclic Graph).

    Task:

    Given a weighted directed graph without negative weight arcs. Find the shortest paths from vertex “1” to all others

    Solution

    We make a table of distances from the vertex “1” to all the others, including the vertex “1”.

    Iteration 0.

    Mark vertex 1 as a base vertex. We know that the distance from vertex 1 to vertex 1 is 0. It is less than infinity. We write it down to the table. For the rest of the vertices, for now, write down the distance value equal to infinity. Select the smallest distance value from the first iteration. This is distance 1-1. Vertex 1 is resolved. Moving on to the next iteration

    # IterVertex 1
    (resolved)
    Vertex 2Vertex 3Vertex 4Vertex 5Vertex 6
    00∞∞∞∞∞

    Iteration 1.

    From vertex 1 you can go to vertex 2 and 3.
    The distance from vertex 1 to vertex 2 will be 0 + 6 = 6 (edge ​​weight 1-2). 6 is less than infinity. We write to the table.
    The distance from vertex 1 to vertex 3 will be 0 + 4 = 4 (edge ​​weight 1-3). 4 is less than infinity. We write to the table.
    Select the smallest distance value from the first iteration. This distance is from 1-3. Vertex 3 is resolved. It is now basic. Moving on to the next iteration

    # IterVertex 1
    (resolved)
    Vertex 2Vertex 3
    (resolved)
    Vertex 4Vertex 5Vertex 6
    00∞∞∞∞∞
    164∞∞∞

    Iteration 2.

    From vertex 3 you can go to vertex 4 and 5.
    The distance from vertex 3 to vertex 4 will be 4 + 3 = 7. 7 is less than infinity. We write to the table.
    The distance from vertex 3 to vertex 5 will be 4 + 8 = 12. 12 less than infinity. We write to the table.
    Transfer the distance value 1-2 to the second iteration without changes.
    Select the smallest distance value from the second iteration. This distance is from 1-2. Vertex 2 is resolved. Vertex 2 is now basic. Moving on to the next iteration

    # IterVertex 1
    (res-d)
    Vertex 2
    (res-d)
    Vertex 3
    (res-d)
    Vertex 4Vertex 5Vertex 6
    00∞∞∞∞∞
    164∞∞∞
    26712∞

    Iteration 3.

    From vertex 2 you can go to vertex 4, 5, and 6.
    The distance from vertex 2 to vertex 4 will be 6 + 7 = 13. 13 is greater than 7, which is already in the table. We transfer the value from the previous iteration to the current one.
    The distance from vertex 2 to vertex 5 will be 6 + 4 = 10. 10 is less than 12. Write it down in the table.
    The distance from vertex 2 to vertex 6 will be 6 + 2 = 8. 8 is less than infinity. We write to the table.
    Select the smallest distance value from the third iteration. This distance is from 1-4. Vertex 4 is resolved. Vertex 4 is now basic. Moving on to the next iteration

    # IterVertex 1
    (res-d)
    Vertex 2
    (res-d)
    Vertex 3
    (res-d)
    Vertex 4
    (res-d)
    Vertex 5Vertex 6
    00∞∞∞∞∞
    164∞∞∞
    26712∞
    37108

    Iteration 4.

    From vertex 4, you can only get to vertex 6.
    The distance from vertex 4 to vertex 6 will be 7 + 10 = 17.17 is greater than 8, which is already in the table. We transfer the value from the previous iteration to the current one.
    The distance value 1-5 is transferred to the second iteration without changes.
    Choose the smallest distance value from the fourth iteration. This distance is from 1-6. Vertex 6 is resolved. Vertex 6 is now basic. Moving on to the next iteration

    # IterVertex 1
    (res-d)
    Vertex 2
    (res-d)
    Vertex 3
    (res-d)
    Vertex 4
    (res-d)
    Vertex 5Vertex 6
    (res-d)
    00∞∞∞∞∞
    164∞∞∞
    26712∞
    37108
    4108

    Iteration 5.

    From vertex 5, you can only go to vertex 6.
    The distance from vertex 5 to vertex 6 will be 10 + 1 = 11. 11 is greater than 8, which is already in the table. We transfer the value from the previous iteration to the current one.
    Vertex 5 has been resolved.

    All vertices are resolved. The algorithm is complete. The shortest distances from vertex 1 to all other vertices can be seen in the table.

    # IterVertex 1Vertex 2Vertex 3Vertex 4Vertex 5Vertex 6
    00∞∞∞∞∞
    164∞∞∞
    26712∞
    37108
    4108
    58

    PlantUML diagram of the algorithm

    PlantUML Syntax:<br /> @startuml</p><p>start</p><p>:Set path from the start point to start point is 0;<br /> :Set start point is base vertex;</p><p>repeat</p><p> :Calculate path from base to neibours as<br /> path to base vertex + edge weight;<br /> if (Path to neibour shortest than already calculated) then (yes)<br /> :Overwrite shortest path;<br /> endif</p><p> repeat<br /> if (Shortest path) then (yes)<br /> :Set vertex with shortest path as resolved;<br /> :Set vertex with shortest path as new base vertex;<br /> endif<br /> repeat while (End of vertex list) is (no)</p><p>repeat while (All vertexes resolved) is (no)</p><p>stop</p><p>@enduml<br /> ” usemap=”#plantuml_map”></p><h2 class=Sample code

    Below you will get link to github repo with Kotlin, Java, and Python code

    Download it from github