Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced B Tree in Data Structure Convert Sorted List to Binary Search Tree Flattening a Linked List Given a Perfect Binary Tree, Reverse Alternate Levels Left View of Binary Tree What are Forest Trees in Data Structure Compare Balanced Binary Tree and Complete Binary Tree Diameter of a Binary Tree Given a Binary Tree Check the Zig Zag Traversal Given a Binary Tree Print the Shortest Path Given a Binary Tree Return All Root To Leaf Paths Given a Binary Tree Swap Nodes at K Height Given a Binary Tree Find Its Minimum Depth Given a Binary Tree Print the Pre Order Traversal in Recursive Given a Generate all Structurally Unique Binary Search Trees Perfect Binary Tree Threaded Binary Trees Function to Create a Copy of Binary Search Tree Function to Delete a Leaf Node from a Binary Tree Function to Insert a Node in a Binary Search Tree Given Two Binary Trees, Check if it is Symmetric A Full Binary Tree with n Nodes Applications of Different Linked Lists in Data Structure B+ Tree in Data Structure Construction of B tree in Data Structure Difference between B-tree and Binary Tree Finding Rank in a Binary Search Tree Finding the Maximum Element in a Binary Tree Finding the Minimum and Maximum Value of a Binary Tree Finding the Sum of All Paths in a Binary Tree Time Complexity of Selection Sort in Data Structure How to get Better in Data Structures and Algorithms Binary Tree Leaf Nodes Classification of Data Structure Difference between Static and Dynamic Data Structure Find the Union and Intersection of the Binary Search Tree Find the Vertical Next in a Binary Tree Finding a Deadlock in a Binary Search Tree Finding all Node of k Distance in a Binary Tree Finding Diagonal Sum in a Binary Tree Finding Diagonal Traversal of The Binary Tree Finding In-Order Successor Binary Tree Finding the gcd of Each Sibling of the Binary Tree Greedy Algorithm in Data Structure How to Calculate Space Complexity in Data Structure How to find missing numbers in an Array Kth Ancestor Node of Binary Tree Minimum Depth Binary Tree Mirror Binary Tree in Data Structure Red-Black Tree Insertion Binary Tree to Mirror Image in Data Structure Calculating the Height of a Binary Search Tree in Data Structure Characteristics of Binary Tree in Data Structure Create a Complete Binary Tree from its Linked List Field in Tree Data Structure Find a Specified Element in a binary Search Tree Find Descendant in Tree Data Structure Find Siblings in a Binary Tree Given as an Array Find the Height of a Node in a Binary Tree Find the Second-Largest Element in a Binary Tree Find the Successor Predecessor of a Binary Search Tree Forest of a Tree in Data Structure In Order Traversal of Threaded Binary Tree Introduction to Huffman Coding Limitations of a Binary Search Tree Link State Routing Algorithm in Data Structure Map Reduce Algorithm for Binary Search Tree in Data Structure Non-Binary Tree in Data Structure Quadratic Probing Example in Hashing Scope and Lifetime of Variables in Data Structure Separate Chaining in Data Structure What is Dynamic Data Structure Separate Chaining vs Open Addressing Time and Space Complexity of Linear Data Structures Abstract Data Types in Data Structures Binary Tree to Single Linked List Count the Number of Nodes in the Binary Tree Count Total No. of Ancestors in a Binary Search Tree Elements of Dynamic Programming in Data Structures Find cost of tree with prims algorithm in data structures Find Preorder Successor in a Threaded Binary Tree Find Prime Nodes Sum Count in Non-Binary Tree Find the Right Sibling of a Binary Tree with Parent Pointers Find the Width of the Binary Search Tree Forest trees in Data Structures Free Tree in Data Structures Frequently asked questions in Tree Data Structures Infix, Postfix and Prefix Conversion Time Complexity of Fibonacci Series What is Weighted Graph in Data Structure Disjoint Set ADT in Data Structure Binary Tree to Segment Tree Binary Tree to List in Order State Space Tree for 4 Queen Problem Hash Function Booth Algorithm Flowchart What is an Algorithm Master Theorem Top-down and Bottom-up Approach in Data Structure Base Address of Array Insertion into a Max Heap in Data Structure Delete a Node From Linked List Find Loop in Linked List How to implement Forward DNS Lookup Cache? How to Implement Reverse DNS Look Up Cache? Primitive vs non primitive data structure Concurrency Algorithms GCD Using Recursion Priority Queue using Linked List Difference between Array and Structure Conversion of Binary to Gray Code

Primitive vs non primitive data structure

Introduction

In computer science and programming, data structures are important for effectively organizing and storing data. They are treated as the building blocks for developing efficient algorithms which optimize program performance. Data structures can be classified into two categories: primitive and non-primitive. This article will discuss the characteristics, applications, and differences between these two types of data structures.

There are two types of data structures.

  • Primitive Data Structures
  • Non-primitive Data Structure
Primitive vs non primitive data structure

Differences between Primitive and Non-Primitive Data Structures

Primitive vs non primitive data structure
PrimitiveNon- Primitive
Primitive data structures have a fixed size and consume constant memory, regardless of the amount of data stored.  Non-primitive data structures require additional memory to store metadata and provide a dynamic allocation of memory based on the data size.  
Primitive data structures have limited flexibility in terms of operations and data organization.  Non-primitive data structures offer more flexibility, allowing complex operations, dynamic resizing, and hierarchical relationships between data elements.
Primitive data structures are simple and straightforward, with basic operations and constant time complexity.  Non-primitive data structures offer more flexibility, allowing complex operations, dynamic resizing, and hierarchical relationships between data elements.
Primitive data structures are straightforward, with basic operations and constant time complexity.  Non-primitive data structures can be more complex, with varying time complexity for different operations, depending on the structure's size and organization.
Primitive data structures are usually built into programming languages, with direct support from compilers and interpreters.  Non-primitive data structures require custom implementation using primitive data types and programming constructs.  

Primitive Data Structures:

Primitive data structures are fundamental and built-in data types provided by programming languages. They are typically simple and have a fixed size. Examples of primitive data structures include integers, floating-point numbers, characters, booleans, and pointers. Here are some key aspects of primitive data structures:

  • Primitive data structures are atomic, meaning they cannot be broken down into smaller components.
  • They have a predefined range of values and operations associated with them.
  • The hardware directly supports them and is often represented using a fixed number of bits.
  • They are lightweight in terms of memory consumption and are optimized for performance.

Primitive data structures are commonly used for simple and basic operations in programming, such as arithmetic calculations, logical comparisons, and storing individual data elements. They serve as the building blocks for more complex data structures and algorithms.

Example

Integer

# Declare and assign an integer

num = 10

Floating-point Number

# Declare and assign a floating-point number

pi = 3.14159

Character

# Declare and assign a character

char = 'A'

Boolean

# Declare and assign a boolean value

is_true = True

Array

# Declare and assign an array

numbers = [1, 2, 3, 4, 5]

Applications:

  • Primitive data structures are widely used in various programming scenarios, such as arithmetic operations, logical comparisons, and basic data manipulation.
  • They serve as the foundation for more complex data structures and algorithms.
  • Primitive data structures are essential for low-level programming, requiring direct control over memory and hardware.

Non-Primitive Data Structure

Non-primitive data structures are derived from primitive data types and offer more flexibility in storing and organizing data. They are also known as composite or abstract data types. Non-primitive data structures can be categorized into two main types: linear and nonlinear. Let's explore their characteristics and applications:

Further, Non-primitive Data Structure is classified into two types

  • Linear
  • Non-Linear

Linear Data Structures:

  • Linear data structures organize data elements sequentially, one after another. Examples include arrays, linked lists, stacks, and queues.
  • They allow easy access to data elements using indexes or pointers.
  • Linear data structures are useful for scenarios involving iterative processing, searching, sorting, and managing data in a specific order.

Furthermore, Linear is Divided into two parts

  • Statics
  • Dynamic

Static: Fixed-size collections of elements stored in contiguous memory locations. The size is predetermined at compile time and cannot be changed during runtime.

  • Array - An array is a collection of elements of the same type arranged in contiguous memory locations. Once the size of an array is defined, it cannot be changed during program execution.

Dynamic: Resizable arrays that can grow or shrink dynamically as needed. They allocate a new block of memory when the capacity is exceeded.

Now Dynamic is Classified into three types

  • Linked List
  • Stack
  • Queue
  • Linked List - A linked list is a linear data structure in computer science; linked lists are widely used in various applications and are fundamental to understanding data structures and algorithms. The linked list is called "linked" because these references connect or link the nodes.

Implementation of a Linked List data structure in Python

class Node:

    def __init__(self, value):

        self.value = value

        self.next = None

class LinkedList:

    def __init__(self):

        self.head = None

    def append(self, value):

        new_node = Node(value)

        if self.head is None:

            self.head = new_node

        else:

            current = self.head

            while current.next:

                current = current.next

            current.next = new_node

    def display(self):

        current = self.head

        while current:

            print(current.value, end=" ")

            current = current.next

        print()

# Example usage

linked_list = LinkedList()

linked_list.append(10)

linked_list.append(20)

linked_list.append(30)

linked_list.display()

Output

Primitive vs non primitive data structure
  • Stack: A Last-In-First-Out (LIFO) data structure where elements are added and removed from the top of the stack. It follows a "push" operation to add elements and a "pop" operation to remove elements.

Implementation of a stack data structure in Python

class Stack:

    def __init__(self):

        self.stack = []

    def push(self, value):

        self.stack.append(value)

    def pop(self):

        if self.is_empty():

            return None

        return self.stack.pop()

    def is_empty(self):

        return len(self.stack) == 0

    def peek(self):

        if self.is_empty():

            return None

        return self.stack[-1]

# Example usage

stack = Stack()

stack.push(10)

stack.push(20)

stack.push(30)

print(stack.peek())  # Output: 30

print(stack.pop())  # Output: 30

print(stack.pop())  # Output: 20

Output

Primitive vs non primitive data structure
  • Queue - A queue is an abstract data type that works on First-In-First-Out (FIFO) principle. The first element inserted is the first to be removed, similar to people waiting in a queue. Queues are used in scenarios where the order of insertion and removal is significant, such as scheduling, resource allocation, and breadth-first search algorithms. It follows an enqueue to add elements and a dequeue operation to remove them.

Implementation of a queue data structure in Python

class Queue:

    def __init__(self):

        self.queue = []

    def enqueue(self, value):

        self.queue.append(value)

    def dequeue(self):

        if self.is_empty():

            return None

        return self.queue.pop(0)

    def is_empty(self):

        return len(self.queue) == 0

    def peek(self):

        if self.is_empty():

            return None

        return self.queue[0]

# Example usage

queue = Queue()

queue.enqueue(10)

queue.enqueue(20)

queue.enqueue(30)

print(queue.peek())  # Output: 10

print(queue.dequeue())  # Output: 10

print(queue.dequeue())  # Output: 20
Primitive vs non primitive data structure

Nonlinear Data Structures:

Nonlinear data structures are widely used for hierarchical data representation, network analysis, indexing, and efficient data retrieval.

  • Nonlinear data structures organize data elements in a hierarchical or non-sequential manner. Examples include trees, graphs, and hash tables.
  • They provide more complex relationships between data elements, allowing efficient searching, insertion, and deletion operations.
  • Nonlinear data structures are suitable for modeling real-world scenarios, such as hierarchical relationships, network connections, and complex data dependencies.

Nonlinear Data Structures are classified into two type

  • Tree
  • Graph

Tree

Trees are nonlinear data structures mainly composed of nodes connected by edges; there are many types of trees, such as binary trees, binary search trees, balanced trees, heaps, and many more. Below we will see the implementation of the binary tree.

Implementation of Binary Tree in Python

class TreeNode:

    def __init__(self, data):

        self.data = data

        self.left = None

        self.right = None

# Create the binary tree

root = TreeNode(1)

root.left = TreeNode(2)

root.right = TreeNode(3)

root.left.left = TreeNode(4)

root.left.right = TreeNode(5)

# Traverse the binary tree (in-order traversal)

def inorder_traversal(node):

    if node:

        inorder_traversal(node.left)

        print(node.data)

        inorder_traversal(node.right)

print("In-order Traversal:")

inorder_traversal(root)

Output

Primitive vs non primitive data structure

The code is the basic structure of a binary tree and how to perform an in-order traversal recursively. Binary trees are widely used data structures and traversals like in-order, pre-order, and post-order help visit and process nodes in different orders, depending on the desired operation.

Graph

Graphs are nonlinear data structures composed of nodes (vertices) connected by edges.

import networkx as nx

import matplotlib.pyplot as plt

# Create the graph

G = nx.Graph()

# Add nodes

G.add_nodes_from([1, 2, 3, 4, 5])

# Add edges

G.add_edges_from([(1, 2), (1, 3), (2, 4), (2, 5)])

# Visualize the graph

nx.draw(G, with_labels=True)

plt.show()

Note:- Considering these differences is important when selecting the appropriate data structure for a specific programming task.

Conclusion

Both primitive and non-primitive data structures are essential in programming and data management. Primitive data structures provide the basic building blocks for representing simple data types efficiently. On the other hand, non-primitive data structures offer more flexibility, allowing complex data organization, efficient searching, and dynamic resizing. Understanding the characteristics and differences between these two types of data structures is crucial for selecting the appropriate structure to optimize program performance and achieve efficient data management in various programming scenarios.