The Wayback Machine - https://web.archive.org/web/20241121120046/https://www.geeksforgeeks.org/tug-of-war/
Open In App

Tug of War

Last Updated : 11 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a set of n integers, divide the set in two subsets of n/2 sizes each such that the absolute difference of the sum of two subsets is as minimum as possible. If n is even, then sizes of two subsets must be strictly n/2 and if n is odd, then size of one subset must be (n-1)/2 and size of other subset must be (n+1)/2.
For example, let given set be {3, 4, 5, -3, 100, 1, 89, 54, 23, 20}, the size of set is 10. Output for this set should be {4, 100, 1, 23, 20} and {3, 5, -3, 89, 54}. Both output subsets are of size 5 and sum of elements in both subsets is same (148 and 148). 
Let us consider another example where n is odd. Let given set be {23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4}. The output subsets should be {45, -34, 12, 98, -1} and {23, 0, -99, 4, 189, 4}. The sums of elements in two subsets are 120 and 121 respectively.
The following solution tries every possible subset of half size. If one subset of half size is formed, the remaining elements form the other subset. We initialize current set as empty and one by one build it. There are two possibilities for every element, either it is part of current set, or it is part of the remaining elements (other subset). We consider both possibilities for every element. When the size of current set becomes n/2, we check whether this solutions is better than the best solution available so far. If it is, then we update the best solution.
Following is the implementation for Tug of War problem. It prints the required arrays. 
 

C++




#include <bits/stdc++.h>
using namespace std;
  
// function that tries every possible solution by calling itself recursively
void TOWUtil(int* arr, int n, bool* curr_elements, int no_of_selected_elements,
             bool* soln, int* min_diff, int sum, int curr_sum, int curr_position)
{
    // checks whether the it is going out of bound
    if (curr_position == n)
        return;
  
    // checks that the numbers of elements left are not less than the
    // number of elements required to form the solution
    if ((n/2 - no_of_selected_elements) > (n - curr_position))
        return;
  
    // consider the cases when current element is not included in the solution
    TOWUtil(arr, n, curr_elements, no_of_selected_elements,
              soln, min_diff, sum, curr_sum, curr_position+1);
  
    // add the current element to the solution
    no_of_selected_elements++;
    curr_sum = curr_sum + arr[curr_position];
    curr_elements[curr_position] = true;
  
    // checks if a solution is formed
    if (no_of_selected_elements == n/2)
    {
        // checks if the solution formed is better than the best solution so far
        if (abs(sum/2 - curr_sum) < *min_diff)
        {
            *min_diff = abs(sum/2 - curr_sum);
            for (int i = 0; i<n; i++)
                soln[i] = curr_elements[i];
        }
    }
    else
    {
        // consider the cases where current element is included in the solution
        TOWUtil(arr, n, curr_elements, no_of_selected_elements, soln,
                  min_diff, sum, curr_sum, curr_position+1);
    }
  
    // removes current element before returning to the caller of this function
    curr_elements[curr_position] = false;
}
  
// main function that generate an arr
void tugOfWar(int *arr, int n)
{
    // the boolean array that contains the inclusion and exclusion of an element
    // in current set. The number excluded automatically form the other set
    bool* curr_elements = new bool[n];
  
    // The inclusion/exclusion array for final solution
    bool* soln = new bool[n];
  
    int min_diff = INT_MAX;
  
    int sum = 0;
    for (int i=0; i<n; i++)
    {
        sum += arr[i];
        curr_elements[i] =  soln[i] = false;
    }
  
    // Find the solution using recursive function TOWUtil()
    TOWUtil(arr, n, curr_elements, 0, soln, &min;_diff, sum, 0, 0);
  
    // Print the solution
    cout << "The first subset is: ";
    for (int i=0; i<n; i++)
    {
        if (soln[i] == true)
            cout << arr[i] << " ";
    }
    cout << "\nThe second subset is: ";
    for (int i=0; i<n; i++)
    {
        if (soln[i] == false)
            cout << arr[i] << " ";
    }
}
  
// Driver program to test above functions
int main()
{
    int arr[] = {23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4};
    int n = sizeof(arr)/sizeof(arr[0]);
    tugOfWar(arr, n);
    return 0;
}


Java




// Java program for Tug of war
import java.util.*;
import java.lang.*;
import java.io.*;
  
class TugOfWar
{
    public int min_diff;
      
    // function that tries every possible solution
    // by calling itself recursively
    void TOWUtil(int arr[], int n, boolean curr_elements[],
               int no_of_selected_elements, boolean soln[],
               int sum, int curr_sum, int curr_position)
    {
        // checks whether the it is going out of bound
        if (curr_position == n)
            return;
  
        // checks that the numbers of elements left 
        // are not less than the number of elements
        // required to form the solution
        if ((n / 2 - no_of_selected_elements) >
                (n - curr_position))
            return;
  
        // consider the cases when current element 
        // is not included in the solution
        TOWUtil(arr, n, curr_elements, 
               no_of_selected_elements, soln, sum,
               curr_sum, curr_position+1);
  
        // add the current element to the solution
        no_of_selected_elements++;
        curr_sum = curr_sum + arr[curr_position];
        curr_elements[curr_position] = true;
  
        // checks if a solution is formed
        if (no_of_selected_elements == n / 2)
        {
            // checks if the solution formed is
            // better than the best solution so
            // far
            if (Math.abs(sum / 2 - curr_sum) <
                                  min_diff)
            {
                min_diff = Math.abs(sum / 2 -
                                  curr_sum);
                for (int i = 0; i < n; i++)
                    soln[i] = curr_elements[i];
            }
        }
        else
        {
            // consider the cases where current 
            // element is included in the 
            // solution
            TOWUtil(arr, n, curr_elements, 
                    no_of_selected_elements, 
                    soln, sum, curr_sum, 
                    curr_position + 1);
        }
  
        // removes current element before 
        // returning to the caller of this
        // function
        curr_elements[curr_position] = false;
    }
  
    // main function that generate an arr
    void tugOfWar(int arr[])
    {
        int n = arr.length; 
  
        // the boolean array that contains the 
        // inclusion and exclusion of an element
        // in current set. The number excluded
        // automatically form the other set
        boolean[] curr_elements = new boolean[n];
          
        // The inclusion/exclusion array for 
        // final solution
        boolean[] soln = new boolean[n];
  
        min_diff = Integer.MAX_VALUE;
  
        int sum = 0;
        for (int i = 0; i < n; i++)
        {
            sum += arr[i];
            curr_elements[i] = soln[i] = false;
        }
  
        // Find the solution using recursive 
        // function TOWUtil()
        TOWUtil(arr, n, curr_elements, 0, 
                soln, sum, 0, 0);
  
        // Print the solution
        System.out.print("The first subset is: ");
        for (int i = 0; i < n; i++)
        {
            if (soln[i] == true)
                System.out.print(arr[i] + " ");
        }
        System.out.print("\nThe second subset is: ");
        for (int i = 0; i < n; i++)
        {
            if (soln[i] == false)
                System.out.print(arr[i] + " ");
        }
    }
      
    // Driver program to test above functions
    public static void main (String[] args) 
    {
        int arr[] = {23, 45, -34, 12, 0, 98,
                     -99, 4, 189, -1, 4};
        TugOfWar a = new TugOfWar();
        a.tugOfWar(arr);
    }
}
  
// This code is contributed by Chhavi


Python3




# Python3 program for above approach
  
# function that tries every possible 
# solution by calling itself recursively 
def TOWUtil(arr, n, curr_elements, no_of_selected_elements, 
            soln, min_diff, Sum, curr_sum, curr_position):
      
    # checks whether the it is going 
    # out of bound 
    if (curr_position == n): 
        return
  
    # checks that the numbers of elements 
    # left are not less than the number of
    # elements required to form the solution 
    if ((int(n / 2) - no_of_selected_elements) > 
                          (n - curr_position)):
        return
  
    # consider the cases when current element 
    # is not included in the solution 
    TOWUtil(arr, n, curr_elements, no_of_selected_elements, 
            soln, min_diff, Sum, curr_sum, curr_position + 1) 
  
    # add the current element to the solution 
    no_of_selected_elements += 1
    curr_sum = curr_sum + arr[curr_position] 
    curr_elements[curr_position] = True
  
    # checks if a solution is formed 
    if (no_of_selected_elements == int(n / 2)):
          
        # checks if the solution formed is better 
        # than the best solution so far 
        if (abs(int(Sum / 2) - curr_sum) < min_diff[0]):
            min_diff[0] = abs(int(Sum / 2) - curr_sum)
            for i in range(n):
                soln[i] = curr_elements[i]
    else:
          
        # consider the cases where current
        # element is included in the solution 
        TOWUtil(arr, n, curr_elements, no_of_selected_elements, 
                soln, min_diff, Sum, curr_sum, curr_position + 1)
  
    # removes current element before returning
    # to the caller of this function 
    curr_elements[curr_position] = False
  
# main function that generate an arr 
def tugOfWar(arr, n):
      
    # the boolean array that contains the 
    # inclusion and exclusion of an element 
    # in current set. The number excluded 
    # automatically form the other set 
    curr_elements = [None] * n 
  
    # The inclusion/exclusion array
    # for final solution 
    soln = [None] * n 
  
    min_diff = [999999999999] 
  
    Sum = 0
    for i in range(n):
        Sum += arr[i] 
        curr_elements[i] = soln[i] = False
  
    # Find the solution using recursive
    # function TOWUtil() 
    TOWUtil(arr, n, curr_elements, 0, 
            soln, min_diff, Sum, 0, 0) 
  
    # Print the solution 
    print("The first subset is: ")
    for i in range(n):
        if (soln[i] == True):
            print(arr[i], end = " ")
    print()
    print("The second subset is: ")
    for i in range(n):
        if (soln[i] == False):
            print(arr[i], end = " ")
  
# Driver Code
if __name__ == '__main__':
  
    arr = [23, 45, -34, 12, 0, 98, 
               -99, 4, 189, -1, 4] 
    n = len(arr) 
    tugOfWar(arr, n)
  
# This code is contributed by PranchalK


C#




// C# program for Tug of war 
using System;
  
class GFG 
{ 
    public int min_diff; 
      
    // function that tries every possible solution 
    // by calling itself recursively 
    void TOWUtil(int []arr, int n, Boolean []curr_elements, 
                 int no_of_selected_elements, Boolean []soln, 
                 int sum, int curr_sum, int curr_position) 
    { 
        // checks whether the it is going out of bound 
        if (curr_position == n) 
            return; 
  
        // checks that the numbers of elements left 
        // are not less than the number of elements 
        // required to form the solution 
        if ((n / 2 - no_of_selected_elements) > 
            (n - curr_position)) 
            return; 
  
        // consider the cases when current element 
        // is not included in the solution 
        TOWUtil(arr, n, curr_elements, 
                no_of_selected_elements, soln, sum,
                curr_sum, curr_position + 1); 
  
        // add the current element to the solution 
        no_of_selected_elements++; 
        curr_sum = curr_sum + arr[curr_position]; 
        curr_elements[curr_position] = true; 
  
        // checks if a solution is formed 
        if (no_of_selected_elements == n / 2) 
        { 
            // checks if the solution formed is 
            // better than the best solution so 
            // far 
            if (Math.Abs(sum / 2 - curr_sum) < 
                                   min_diff) 
            { 
                min_diff = Math.Abs(sum / 2 - 
                                    curr_sum); 
                for (int i = 0; i < n; i++) 
                    soln[i] = curr_elements[i]; 
            } 
        } 
        else
        { 
            // consider the cases where current 
            // element is included in the 
            // solution 
            TOWUtil(arr, n, curr_elements, 
                    no_of_selected_elements, 
                    soln, sum, curr_sum, 
                    curr_position + 1); 
        } 
  
        // removes current element before 
        // returning to the caller of this 
        // function 
        curr_elements[curr_position] = false; 
    } 
  
    // main function that generate an arr 
    void tugOfWar(int []arr) 
    { 
        int n = arr.Length; 
  
        // the boolean array that contains the 
        // inclusion and exclusion of an element 
        // in current set. The number excluded 
        // automatically form the other set 
        Boolean[] curr_elements = new Boolean[n]; 
          
        // The inclusion/exclusion array for 
        // final solution 
        Boolean[] soln = new Boolean[n]; 
  
        min_diff = int.MaxValue; 
  
        int sum = 0; 
        for (int i = 0; i < n; i++) 
        { 
            sum += arr[i]; 
            curr_elements[i] = soln[i] = false; 
        } 
  
        // Find the solution using recursive 
        // function TOWUtil() 
        TOWUtil(arr, n, curr_elements, 0, 
                soln, sum, 0, 0); 
  
        // Print the solution 
        Console.Write("The first subset is: "); 
        for (int i = 0; i < n; i++) 
        { 
            if (soln[i] == true) 
                Console.Write(arr[i] + " "); 
        } 
        Console.Write("\nThe second subset is: "); 
        for (int i = 0; i < n; i++) 
        { 
            if (soln[i] == false) 
                Console.Write(arr[i] + " "); 
        } 
    } 
      
    // Driver Code
    public static void Main (String[] args) 
    { 
        int []arr = {23, 45, -34, 12, 0, 98, 
                    -99, 4, 189, -1, 4}; 
        GFG a = new GFG(); 
        a.tugOfWar(arr); 
    } 
} 
  
// This code is contributed by 29AjayKumar


PHP




<?php
// PHP program for above approach
  
// Function that tries every possible
// solution by calling itself recursively 
function TOWUtil(&$arr, $n, &$curr_elements, 
                  $no_of_selected_elements, 
                 &$soln, &$min_diff, $sum, 
                  $curr_sum, $curr_position) 
{ 
    // checks whether the it is going 
    // out of bound 
    if ($curr_position == $n) 
        return; 
  
    // checks that the numbers of elements left 
    // are not less than the number of elements 
    // required to form the solution 
    if ((intval($n / 2) - $no_of_selected_elements) > 
                             ($n - $curr_position)) 
        return; 
  
    // consider the cases when current element 
    // is not included in the solution 
    TOWUtil($arr, $n, $curr_elements, 
            $no_of_selected_elements, 
            $soln, $min_diff, $sum, 
            $curr_sum, $curr_position + 1); 
  
    // add the current element to the solution 
    $no_of_selected_elements++; 
    $curr_sum = ($curr_sum +
                 $arr[$curr_position]); 
    $curr_elements[$curr_position] = true; 
  
    // checks if a solution is formed 
    if ($no_of_selected_elements == intval($n / 2)) 
    { 
        // checks if the solution formed is
        // better than the best solution so far 
        if (abs(intval($sum / 2) - 
                       $curr_sum) < $min_diff) 
        { 
            $min_diff = abs(intval($sum / 2) - 
                                   $curr_sum); 
            for ($i = 0; $i < $n; $i++) 
                $soln[$i] = $curr_elements[$i]; 
        } 
    } 
    else
    { 
        // consider the cases where current 
        // element is included in the solution 
        TOWUtil($arr, $n, $curr_elements, 
                $no_of_selected_elements, $soln, 
                $min_diff, $sum, $curr_sum, 
                $curr_position + 1); 
    } 
  
    // removes current element before 
    // returning to the caller of this function 
    $curr_elements[$curr_position] = false; 
} 
  
// main function that generate an arr 
function tugOfWar(&$arr, $n) 
{ 
    // the boolean array that contains the 
    // inclusion and exclusion of an element 
    // in current set. The number excluded
    // automatically form the other set 
    $curr_elements = array_fill(0, $n, 0);
  
    // The inclusion/exclusion array
    // for final solution 
    $soln = array_fill(0, $n, 0);
  
    $min_diff = PHP_INT_MAX; 
  
    $sum = 0; 
    for ($i = 0; $i < $n; $i++) 
    { 
        $sum += $arr[$i]; 
        $curr_elements[$i] = $soln[$i] = false; 
    } 
  
    // Find the solution using recursive
    // function TOWUtil() 
    TOWUtil($arr, $n, $curr_elements, 0,
            $soln, $min_diff, $sum, 0, 0); 
  
    // Print the solution 
    echo "The first subset is: "; 
    for ($i = 0; $i < $n; $i++) 
    { 
        if ($soln[$i] == true) 
            echo $arr[$i] . " "; 
    } 
    echo "\nThe second subset is: "; 
    for ($i = 0; $i < $n; $i++) 
    { 
        if ($soln[$i] == false) 
            echo $arr[$i] . " "; 
    } 
} 
  
// Driver Code
$arr = array(23, 45, -34, 12, 0, 98,
            -99, 4, 189, -1, 4); 
$n = count($arr); 
tugOfWar($arr, $n); 
  
// This code is contributed
// by rathbhupendra
?>


Javascript




<script>
// javascript program for Tug of war
     var min_diff;
  
    // function that tries every possible solution
    // by calling itself recursively
    function TOWUtil(arr , n,  curr_elements , no_of_selected_elements,  soln , sum,
             curr_sum , curr_position) {
        // checks whether the it is going out of bound
        if (curr_position == n)
            return;
  
        // checks that the numbers of elements left
        // are not less than the number of elements
        // required to form the solution
        if ((parseInt(n / 2) - no_of_selected_elements) > (n - curr_position))
            return;
  
        // consider the cases when current element
        // is not included in the solution
        TOWUtil(arr, n, curr_elements, no_of_selected_elements, soln, sum, curr_sum, curr_position + 1);
  
        // add the current element to the solution
        no_of_selected_elements++;
        curr_sum = curr_sum + arr[curr_position];
        curr_elements[curr_position] = true;
  
        // checks if a solution is formed
        if (no_of_selected_elements == parseInt(n / 2)) {
            // checks if the solution formed is
            // better than the best solution so
            // far
            if (Math.abs(parseInt(sum / 2) - curr_sum) < min_diff) {
                min_diff = Math.abs(parseInt(sum / 2) - curr_sum);
                for (i = 0; i < n; i++)
                    soln[i] = curr_elements[i];
            }
        } else {
            // consider the cases where current
            // element is included in the
            // solution
            TOWUtil(arr, n, curr_elements, no_of_selected_elements, soln, sum, curr_sum, curr_position + 1);
        }
  
        // removes current element before
        // returning to the caller of this
        // function
        curr_elements[curr_position] = false;
    }
  
    // main function that generate an arr
    function tugOfWar(arr) {
        var n = arr.length;
  
        // the boolean array that contains the
        // inclusion and exclusion of an element
        // in current set. The number excluded
        // automatically form the other set
        var curr_elements = Array(n).fill(true);
  
        // The inclusion/exclusion array for
        // final solution
        var soln =  Array(n).fill(false);
  
        min_diff = Number.MAX_VALUE;
  
        var sum = 0;
        for (var i = 0; i < n; i++) {
            sum += arr[i];
            curr_elements[i] = soln[i] = false;
        }
  
        // Find the solution using recursive
        // function TOWUtil()
        TOWUtil(arr, n, curr_elements, 0, soln, sum, 0, 0);
  
        // Print the solution
        document.write("The first subset is: ");
        for (var i = 0; i < n; i++) {
            if (soln[i] == true)
                document.write(arr[i] + " ");
        }
        document.write("<br/>The second subset is: ");
        for (var i = 0; i < n; i++) {
            if (soln[i] == false)
                document.write(arr[i] + " ");
        }
    }
  
    // Driver program to test above functions
        var arr = [ 23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4 ];
        tugOfWar(arr);
  
// This code is contributed by Rajput-Ji
</script>


Output: 

The first subset is: 45 -34 12 98 -1
The second subset is: 23 0 -99 4 189 4

Time Complexity: O(2^n)

SpaceComplexity: O(n)
This article is compiled by Ashish Anand and reviewed by GeeksforGeeks team.
 



Previous Article
Next Article

Similar Reads

Array Data Structure Guide
In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive( at contiguous locations. It offers mainly the following advantag
4 min read
Linked List Data Structure
A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Here’s the comparison of Linked List vs Arrays Linked List: Data Structure: Non-contiguous Memory Allocation:
3 min read
Singly Linked List Tutorial
A singly linked list is a fundamental data structure in computer science and programming, it consists of nodes where each node contains a data field and a reference to the next node in the node. The last node points to null, indicating the end of the list. This linear structure supports efficient insertion and deletion operations, making it widely
15+ min read
Binary Search Tree
A Binary Search Tree (or BST) is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the parent node.
3 min read
Dynamic Programming or DP
This is a complete tutorial on Dynamic Programming (DP) from Theory to Problems ordered Difficulty Wise. DP is an algorithmic technique used in computer science and mathematics to solve complex problems by breaking them down into smaller overlapping subproblems. The core idea behind DP is to store solutions to subproblems so that each is solved onl
3 min read
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. Sorting is provided in library implementation of most of the programming languages. Basics of Sorting Algorithms:Introduction to Sorting Applications of Sorting Sorting Algorithms:Comparison Based : Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Quick
3 min read
Stack Data Structure
A Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first, comes out last. It behaves like a stack of plate
3 min read
Graph Algorithms
Graph algorithms are methods used to manipulate and analyze graphs, solving various range of problems like finding the shortest path, cycles detection. If you are looking for difficulty-wise list of problems, please refer to Graph Data Structure. Basics of Graph:Introduction to GraphsGraph and its representationsTranspose graphBFS and DFS in Graph:
4 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. In this tutorial, we will explore the most commonly used data structures, including arrays, linke
10 min read
DSA Tutorial - Learn Data Structures and Algorithms
Data Structures and Algorithms (DSA) refer to the study of methods for organizing and storing data and the design of procedures (algorithms) for solving problems, which operate on these data structures. DSA is one of the most important skills that every computer science student must have. It is often seen that people with good knowledge of these te
15+ min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of the node. The AVL tree is named after its inventors, Georgy
3 min read
Introduction to Tree Data Structure
Tree data structure is a hierarchical structure that is used to represent and organize data in a way that is easy to navigate and search. It is a collection of nodes that are connected by edges and has a hierarchical relationship between the nodes. The topmost node of the tree is called the root, and the nodes below it are called the child nodes. E
15 min read
Top 50 Array Coding Problems for Interviews
Here is the collection of the Top 50 list of frequently asked interview questions on arrays. Problems in this Article are divided into three Levels so that readers can practice according to the difficulty level step by step. Level 1Problems Practice Find the Minimum and Maximum Element in an Array Solve Array Reverse Solve Write a Program to Cyclic
3 min read
Difference between BFS and DFS
Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search. ParametersBFSDFSStands forBFS stands for Breadth First Search.DFS stands for Depth First Search.Data StructureBFS(Brea
2 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the first pass, the maximum element goes to end (its cor
8 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element and swap it with the first element. This way we get
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data St
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. Table of Content How does QuickSort Algorithm work? Working of Partition Algorithm with IllustrationIllustration of QuickSort Algor
13 min read
Convert Infix expression to Postfix expression
Write a program to convert an Infix expression to Postfix form. Infix expression: The expression of the form "a operator b" (a + b) i.e., when an operator is in-between every pair of operands.Postfix expression: The expression of the form "a b operator" (ab+) i.e., When every pair of operands is followed by an operator. Examples: Input: A + B * C +
11 min read
Heap Sort - Data Structures and Algorithms Tutorials
Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use Binary Heap so that we can quickly find and move t
15 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a sorting algorithm that follows the divide-and-conquer approach. It works by recursively dividing the input array into smaller subarrays and sorting those subarrays then merging them back together to obtain the sorted array. In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each h
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. Then, you pick a card from the unsorted group and p
10 min read
How to find Shortest Paths from Source to all Vertices using Dijkstra's Algorithm
Given a weighted graph and a source vertex in the graph, find the shortest paths from the source to all the other vertices in the given graph. Note: The given graph does not contain any negative edge. Examples: Input: src = 0, the graph is shown below. Output: 0 4 12 19 21 11 9 8 14 Explanation: The distance from 0 to 1 = 4. The minimum distance fr
15+ min read
Prim’s Algorithm for Minimum Spanning Tree (MST)
Introduction to Prim's algorithm:We have discussed Kruskal's algorithm for Minimum Spanning Tree. Like Kruskal's algorithm, Prim’s algorithm is also a Greedy algorithm. This algorithm always starts with a single node and moves through several adjacent nodes, in order to explore all of the connected edges along the way. The algorithm starts with an
15+ min read
Kruskal’s Minimum Spanning Tree (MST) Algorithm
A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, connected, undirected graph is a spanning tree with a weight less than or equal to the weight of every other spanning tree. To learn more about Minimum Spanning Tree, refer to this article. Introduction to Kruskal's Algorithm:Here we will discuss Kruskal's algorithm to fi
15+ min read
Floyd Warshall Algorithm
The Floyd-Warshall algorithm, named after its creators Robert Floyd and Stephen Warshall, is a fundamental algorithm in computer science and graph theory. It is used to find the shortest paths between all pairs of nodes in a weighted graph. This algorithm is highly efficient and can handle graphs with both positive and negative edge weights, making
15+ min read
Breadth First Search or BFS for a Graph
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are traversed. This is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level. A lot of popular graph
15+ min read
0/1 Knapsack Problem
Prerequisites: Introduction to Knapsack Problem, its Types and How to solve them Given N items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum
15+ min read
Depth First Search or DFS for a Graph
Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. Like trees, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. After we finish traversing one adjacent vertex and its reachable vertices,
15+ min read
Tree Traversal Techniques
Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss about all the tree traversal techniques along with their uses. Table o
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg