×

SQL Topological Sorting

It is for Directed Acyclic Graph, which linearly describes the ordering of graphs. It is not possible for all graphs, it is possible for only Directed acyclic graphs.

Applications of Topological Sorting:

  • Find cycles of a graph.
  • Deadlock detection of Operating system.
  • Resolution of dependency.
  • Ordering of sentences.
  • Analysis of critical path.
  • Problem with the course schedule.

Java Code for Topological sorting:

import java.io.*;
import java.util.*;
class ConstructingGraph
 {
    private int Vect;
    private ArrayList < ArrayList <Integer> > ad;
   ConstructingGraph (int vec)
    {
        Vec = vec;
        ad = new ArrayList < ArrayList <Integer> >(v);
        for (int i = 0; i < vec; ++i)
            ad. ad (new ArrayList <Integer> ());
    }
    void adEd (int vec, int wi) 
  { 
    adj. ge (v). add (w); 
   }
    void topologicalSort (int vec, boolean visit[], Stack <Integer> sta)
    {
        visit [v] = true;
        Integer j;
        Iterator <Integer> iter = adj. get (v). iterator();
        while (iter. hasNext()) {
            j = iter.next();
            if (!visit [j])
                topologicalSort (j, visit, sta);
        }
        sta. push (new Integer (vec) );
    }
    void topologicalSort1()
    {
        Stack <Integer> sta = new Stack <Integer> ();
 
        boolean visit [] = new boolean [Vec];
        for (int i = 0; i < Vec; i++)
            visit [i] = false;
         for (int i = 0; i < Vec; i++)
            if (visit [i] == false)
                topologicalSort(i, visit, sta);
        while (sta. empty() == false)
            System.out.print(sta.pop() + " ");
    }
 
    // Driver code
    public static void main(String args[])
    {
        ConstructingGraph obj1 = new ConstructingGraph (6);
        obj1. addEdge (5, 2);
        obj1. addEdge (5, 0);
        obj1. addEdge (4, 0);
        obj1. addEdge (4, 1);
        obj1. addEdge (2, 3);
        obj1. addEdge (3, 1);
 
        System.out.println ( "Topological Sort of the given graph");
        obj1. topologicalSort1 ();
    }
}

Output:

Topological Sort of the given graph
5 4 2 3 1 0

Python code for Topological Sort:

from collections import defaultdict
 
 
class ConstructingGraph:
    def __init__ (self, vert):
        self. gra = defaultdict(list) 
        self. V = vert  
    def adEdg (self, p, q):
        self. gra [p]. append (q)
    def topologicalSort (self, q, visit, sta):
        visit [q] = True
        for i in self. gra [q]:
            if visit [i] == False:
                self. topologicalSort (i, visit, sta)
        sta. append (v)
    def topologicalSort1 (self):
        visit = [False] * self.V
        sta = []
        for i in range(self.V):
            if visit [i] == False:
                self. topologicalSort (i, visit, sta)
        print( sta [::-1]) 
g1 = ConstructingGraph (6)
g1. addEdge (5, 2)
g1. addEdge (5, 0)
g1. addEdge (4, 0)
g1. addEdge (4, 1)
g1. addEdge (2, 3)
g1. addEdge (3, 1)
 
print ("Topological Sort of the given graph")
g.topologicalSort1 ()

Output:

Topological Sort of the given graph
5 4 2 3 1 0

C++ code for Topological Sort:

#include <iostream>
#include <list>
#include <stack>
using namespace std;
class ConstructingGraph 
{
    int Vec;
    list <int> * ad;
    void topologicalSort (int p, bool visit[], stack <int>& Sta);
 
public:
    ConstructingGraph (int Vec);
    void adEdg (int q, int p);
    void topologicalSort1 ();
};
 
Graph :: ConstructingGraph (int Vec)
{
    this -> Vec = Vec;
    ad = new list <int> [Vec];
}
 
void Graph :: adEd (int q, int p)
{
    ad [q]. push_back (p);
}
void Graph :: topologicalSort (int q, bool visit [], stack<int>& Sta)
{
    Visit [q] = true;
    list<int> :: iterator j;
    for (j = ad [q]. begin (); i != ad[q]. end (); ++i)
        if (!visited [*j])
            topologicalSort (*j, visit, Sta);
    Sta. push (v);
}
 
void Graph :: topologicalSort1 ()
{
    stack<int> Sta;
 
    // Mark all the vertices as not visited
    bool* visit = new bool [Vec];
    for (int i = 0; i < Vec; i++)
        visit [i] = false;
 
    // Call the recursive helper function
    // to store Topological
    // Sort starting from all
    // vertices one by one
    for (int i = 0; i < Vec; i++)
        if (visit[i] == false)
            topologicalSort (i, visited, Sta);
 
    // Print contents of stack
    while (Sta. empty () == false) {
        cout << Sta.top() << " ";
        Sta. pop ();
    }
}
 
// Driver Code
int main()
{
    // Create a graph given in the above diagram
    ConstructingGraph G1 (6);
    G1. addEdge (5, 2);
    G1. addEdge (5, 0);
    G1. addEdge (4, 0);
    G1. addEdge (4, 1);
    G1. addEdge (2, 3);
    G1. addEdge (3, 1);
 
    cout <<”Topological Sort of the given "
            "graph \n";
 
    // Function Call
    G1. topologicalSort ();
 
    return 0;
}

Output:

Topological Sort of the given graph
5 4 2 3 1 0

Related Topics

SQL Primary Key

A field, which contains unique data in a table, is called a PRIMARY KEY (PK). It means, a PRIMARY KEY field must contain unique data in the table. A PRIMARY KEY...

4 minutes read.

SQL Cloning Tables

Cloning a Table: To create a copy of the table. To perform the operations, without affecting the actual table. Steps for creating a Cloning Table: Step 1: Empty Table Creation The syntax for Creating...

3 minutes read.

SQL INSERT INTO SELECT

In this tutorial, we will help you to understand and learn how to copy records from one table and add them to another table in the SQL with the help...

5 minutes read.

SQL CROSS Join

In this tutorial, we will help you understand the concept of the SQL CROSS Join clause with the few examples. The SQL CROSS Join query is used to join one or...

5 minutes read.

SQL Create Database

This tutorial will help us understand how to CREATE a Database in SQL with a few examples. The first step for storing structured records in the database is creating the databases. We...

4 minutes read.

SET Operators in SQL

The operator used to join or combine two queries is none other than SET operators. Operators categorized into SET operators are as follows: UNION Operator.UNION ALL’ Operator.INTERSECT Operator.MINUS Operator. Rules to be...

8 minutes read.

SQL INSERT Table

In this tutorial, we will help you to understand and learn how to add records to the table in SQL with the help of examples. SQL INSERT query is used to...

5 minutes read.

Grant Command in SQL

What is DCL (Data Control Language)? Data Control Language (DCL) is a computer programming language with syntax intended to manage access to data kept in databases. It is a part of...

3 minutes read.

SQL LOGICAL Operator

In this tutorial, we will understand the operator who falls under the logical operator in SQL with the help of examples. The SQL Logical Operator displays the query result in one...

5 minutes read.

GROUP BY vs ORDER BY

The GROUP BY clause and ORDER BY clause in SQL are used to arrange data obtained by SQL queries. The important difference between the GROUP BY clause and ORDER BY...

4 minutes read.

SQL Left Join

The SQL Left Join query displays all the records from the table and displays similar records from the right table. The query displays zero records if it doesn’t find any...

4 minutes read.

SQL Truncate

This command deletes all records from table. Truncate is a DDL command. Syntax: TRUNCATE table table_name; Example: Truncate table teacher; ORDER BY The ORDER BY clause arranges the table or column in ascending...

5 minutes read.

SQL SELECT WHERE Clause

In this SQL section, we will help you understand the concept of the SQL SELECT WHERE clause with a few examples. The WHERE clause in SELECT query displays those records as...

5 minutes read.

SQL Alter Table

In Structured Query Language, if you want to add columns in an existing table, then modify the table, or delete columns from the table. All these operations are allowed only...

7 minutes read.

SQL JOIN

As the name says, joins mean to merge something or to combine something. But in the case of SQL, joins mean to merge or combine two different tables. The Join clause...

12 minutes read.

SQL Handling Duplicate

Removing Duplicates using DISTINCT Keyword: By using the DISTINCT keyword in SQL we can remove duplicate characters from tables or databases. A table contains more duplicate values and duplicate values can cause...

4 minutes read.

Check Constraint in SQL

The Check Constraint in SQL is the rule or set of rules used to limit the data range that can be entered in a table column. Check constraint is used...

8 minutes read.

SQL Aggregate Functions

In this tutorial, we will learn and understand the SQL Aggregate Functions concept with the help of examples. SQL Aggregate Function is a function used to perform calculation operations on one...

4 minutes read.

Introduction to SQL

SQL Introduction SQL is Standard Query Language. This language is used to communicate or interact with database. In other words, SQL is used to access and manage data or information...

2 minutes read.

How to create a database in SQL?

How to create a database in SQL It is very necessary to create a database in order to store the data into the database.Database name must always be unique.SQL does not...

6 minutes read.