Sunteți pe pagina 1din 12

Data Structure through C

data structure is a data organization, management and storage format that enables efficient access and modification. More
precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be
applied to the data.

Data structure are classified into two type such as linear or non-linear.

Linear: A data structure is said to be linear if its elements form a sequence. The elements of linear data
structure represents by means of sequential memory locations. The other way is to have the linear
relationship between the elements represented by means of pointers or links. Ex- Array and Link List.

Non-linear: A data structure is said to be non-linear if its elements a hierarchical relationship between
elements such as trees and graphs. All elements assign the memory as random form and you can fetch
data elements through random access process.
Following operations can be performed on the data structures:
1. Traversing
2. Searching
3. Inserting
4. Deleting
5. Sorting
6. Merging
1. Traversing- It is used to access each data item exactly once so that it can be processed.
2. Searching- It is used to find out the location of the data item if it exists in the given collection of data
items.
3. Inserting- It is used to add a new data item in the given collection of data items.
4. Deleting- It is used to delete an existing data item from the given collection of data items.
5. Sorting- It is used to arrange the data items in some order i.e. in ascending or descending order in
case of numerical data and in dictionary order in case of alphanumeric data.
6. Merging- It is used to combine the data items of two sorted files into single file in the sorted form.

Arrays:
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

1 2 3 4 5 6 7 8 9 10

Insert element from an array


C program to insert an element in an array, for example, consider an array a[10] having three elements in
it initially and a[0] = 1, a[1] = 2 and a[2] = 3 and you want to insert a number 45 at location 1 i.e. a[0] =
45, so we have to move elements one step below so after insertion a[1] = 1 which was a[0] initially, and
a[2] = 2 and a[3] = 3. Array insertion does not mean increasing its size i.e array will not contain 11
elements.
Delete element from an array:

C program to delete an element in an array: This program deletes or removes an element from an array. A
user will enter the position at which the array element deletion is required. Deleting an element does not
affect the size of the array. It also checks whether deletion is possible or not, for example, if an array
contains five elements and user wants to delete the element at the sixth position, it isn't possible.

Merging of two arrays


C program to merge two arrays into the third array: Arrays are assumed to be sorted in ascending
order. You enter two short sorted arrays and combine them to get a larger array. If the arrays are not
sorted then you can sort them first and then use the merge function, another method is to merge them
and then sort the array. Sorting two smaller arrays will take less time as compared to sorting a big array.
Merging two sorted lists is used in merge sort algorithm.
Concatenate two arrays:

Linear Search vs Binary Search


Prerequisite:

 Linear Search
 Binary Search
A linear search scans one item at a time, without jumping to any item .
1. The worst case complexity is O(n), sometimes known an O(n) search
2. Time taken to search elements keep increasing as the number of elements are increased.
A binary search however, cut down your search to half as soon as you find middle of a sorted list.
1. The middle element is looked to check if it is greater than or less than the value to be searched.
2. Accordingly, search is done to either half of the given list
Important Differences
 Input data needs to be sorted in Binary Search and not in Linear Search
 Linear search does the sequential access whereas Binary search access data randomly.
 Time complexity of linear search -O(n) , Binary search has time complexity O(log n).
 Linear search performs equality comparisons and Binary search performs ordering comparisons
Let us look at an example to compare the two:
Linear Search to find the element “J” in a given sorted list from A-X

Binary Search to find the element “J” in a given sorted list from A-X
Bubble sort:
C program for bubble sort: C programming code for bubble sort to sort numbers or arrange them in
ascending order. You can modify it to print numbers in descending order. You can also sort strings using
Bubble sort, it is less efficient as its average and worst case complexity is high, there are many other fast
sorting algorithms like quick-sort, heap-sort, etc. Sorting simplifies problem-solving in computer
programming.
Sparse Matrix:

Sparse Matrix and its representations Using Arrays


A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values. If most of the
elements of the matrix have 0 value, then it is called a sparse matrix.
Why to use Sparse Matrix instead of simple matrix?
 Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those
elements.
 Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero
elements..
Example:
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
0 2 6 0 0
Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in most
of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means storing
non-zero elements with triples- (Row, Column, value).
Sparse Matrix Representations can be done in many ways following are two common representations:

Method 1: Using Arrays


2D array is used to represent a sparse matrix in which there are three rows named as

 Row: Index of row, where non-zero element is located


 Column: Index of column, where non-zero element is located
 Value: Value of the non zero element located at index – (row,column)
Matrix addition
Matrix addition in C: C program to add two matrices, i.e., compute the sum of two matrices and then print
it. Firstly a user will be asked to enter the order of matrix (number of rows and columns) and then two
matrices. For example, if a user input order as 2, 2, i.e., two rows and two columns and matrices as
First matrix:
12
34
Second matrix:
45
-1 5
then the output of the program (Summation of the two matrices) is:
57
29

Stack:
A stack data structure can be implemented using one dimensional array. But stack implemented
using array stores only fixed number of data values. This implementation is very simple. Just
define a one dimensional array of specific size and insert or delete the values into that array by
using LIFO(Last In First Out) principle with the help of a variable called 'top'. Initially top is set
to -1. Whenever we want to insert a value into the stack, increment the top value by one and
then insert. Whenever we want to delete a value from the stack, then delete the top value and
decrement the top value by one.

Stack Operations using Array


A stack can be implemented using array as follows...

Before implementing actual operations, first follow the below steps to create an empty stack.

 Step 1 - Include all the header files which are used in the program and define a constant 'MAX' with
specific value.
 Step 2 - Declare all the functions used in stack implementation.
 Step 3 - Create a one dimensional array with fixed size (int stack[MAX])
 Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)
 Step 5 - In main method, display menu with list of operations and make suitable function calls to
perform operation selected by the user on the stack.

push(value) - Inserting value into the stack


In a stack, push() is a function used to insert an element into the stack. In a stack, the new element is always
inserted at top position. Push function takes one integer value as parameter and inserts that value into the
stack. We can use the following steps to push an element on to the stack...

 Step 1 - Check whether stack is FULL. (top == MAX-1)


 Step 2 - If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and terminate the
function.
 Step 3 - If it is NOT FULL, then increment top value by one (top++) and set stack[top] to value
(stack[top] = value).

pop() - Delete a value from the Stack


In a stack, pop() is a function used to delete an element from the stack. In a stack, the element is always
deleted from top position. Pop function does not take any value as parameter. We can use the following steps
to pop an element from the stack...

 Step 1 - Check whether stack is EMPTY. (top == -1)


 Step 2 - If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and terminate
the function.
 Step 3 - If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top--).
display() - Displays the elements of a Stack
We can use the following steps to display the elements of a stack...

 Step 1 - Check whether stack is EMPTY. (top == -1)


 Step 2 - If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
 Step 3 - If it is NOT EMPTY, then define a variable 'i' and initialize with top. Display stack[i] value and
decrement i value by one (i--).
 Step 3 - Repeat above step until i value becomes '0'.

Applications of STACK:
1. During function calls
2. recursive functions
3. Infix expression to postfix expression coversion
4. Postfix expression evaluation
5. Backtracking
6. Compiler design aspects (parsing)
Program for STACK:
#include<stdio.h>
#define MAX 5
int s[MAX],tos=-1;
void push(int);
int pop();
void disp();
int main()
{
int ch,ele;
do{
printf("\nMENU\n1.Push()\n2.Pop()\n3.Display\n4.Exit\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf(" Enter to be insert ele: ");
scanf("%d",&ele);
push(ele);
break;
case 2:
ele=pop();
printf(" the pop item from stack is: %d",ele);
break;
case 3:
disp();
break;
case 4:
printf("End of program: ");
break;
default:
printf(" Invalid choice: ");
}
}while(ch!=4);
return 0;
}
void push(int ele)
{
if(tos==MAX-1)
{
printf(" stack is full: ");
}
else
{
tos++;
s[tos]=ele;
printf("element inserted successfully: ");
}
}
int pop()
{
if(tos==-1)
{
printf(" stack is empty:");
return 0;
}
else
{
int item=s[tos];
tos--;
return item;
}
}

void disp()
{
int i;
if(tos==-1)
{
printf(" stack is empty:");
}
else
{
for(i=tos;i>=0;i--)
{
printf(" %d\n",s[i]);
}
}
}

Ouput:
MENU MENU
1.Push() 1.Push()
2.Pop() 2.Pop()
3.Display 3.Display
4.Exit 4.Exit
Enter your choice: 1 Enter your choice: 2
Enter to be insert ele: 10 the pop item from stack is: 50
element inserted successfully: MENU
MENU 1.Push()
1.Push() 2.Pop()
2.Pop() 3.Display
3.Display 4.Exit
4.Exit Enter your choice: 2
Enter your choice: 1 the pop item from stack is: 40
Enter to be insert ele: 20 MENU
element inserted successfully: 1.Push()
MENU 2.Pop()
1.Push() 3.Display
2.Pop() 4.Exit
3.Display Enter your choice: 2
4.Exit the pop item from stack is: 20
Enter your choice: 1 MENU
Enter to be insert ele: 30 1.Push()
element inserted successfully: 2.Pop()
MENU 3.Display
1.Push() 4.Exit
2.Pop() Enter your choice: 2
3.Display the pop item from stack is: 10
4.Exit MENU
Enter your choice: 1 1.Push()
Enter to be insert ele: 40 2.Pop()
element inserted successfully: 3.Display
MENU 4.Exit
1.Push() Enter your choice: 2
2.Pop() stack is empty: the pop item from stack is: 0
3.Display MENU
4.Exit 1.Push()
Enter your choice: 1 2.Pop()
Enter to be insert ele: 50 3.Display
element inserted successfully: 4.Exit
MENU Enter your choice: 5
1.Push() Invalid choice:
2.Pop() MENU
3.Display 1.Push()
4.Exit 2.Pop()
Enter your choice: 1 3.Display
Enter to be insert ele: 60 4.Exit
stack is full: Enter your choice: 4
MENU End of program:
1.Push() --------------------------------
2.Pop() Process exited after 54.23 seconds with return
3.Display value 0
4.Exit
Enter your choice: 3 Press any key to continue . . .
50
40
30
20
10
MENU
1.Push()
2.Pop()
3.Display
4.Exit
Enter your choice: 1
Enter to be insert ele: 60
stack is full:

Queue Data Structure:

A queue is a useful data structure in programming. It is similar to the ticket queue outside a cinema hall, where the first
person entering the queue is the first person who gets the ticket.

Queue follows the First In First Out(FIFO) rule - the item that goes in first is the item that comes out first too.
In the above image, since 1 was kept in the queue before 2, it was the first to be removed from the queue as well. It follows
the FIFO rule.
In programming terms, putting an item in the queue is called an "enqueue" and removing an item from the queue is called
"dequeue".
We can implement queue in any programming language like C, C++, Java, Python or C#, but the specification is pretty much
the same.

Queue Specifications
A queue is an object or more specifically an abstract data structure(ADT) that allows the following operations:
 Enqueue: Add element to end of queue
 Dequeue: Remove element from front of queue
 Display: Display elements from FRONT to REAR if queue is not empty
 IsEmpty: Check if queue is empty
 IsFull: Check if queue is full
How Queue Works
Queue operations work as follows:
1. Two pointers called FRONT and REAR are used to keep track of the first and last elements in the queue.
2. When initializing the queue, we set the value of FRONT and REAR to -1.
3. On enqueing an element, we increase the value of REAR index and place the new element in the position pointed to
by REAR.
4. On dequeueing an element, we return the value pointed to by FRONT and increase the FRONT index.
5. Before enqueing, we check if queue is already full.
6. Before dequeuing, we check if queue is already empty.
7. When enqueing the first element, we set the value of FRONT to 0.
8. When dequeing the last element, we reset the values of FRONT and REAR to -1.
Applications of QUEUE
1. In Operating system, to process the scheduling on processes.

Program for QUEUE:

Execution:

Circular Queue:

Circular Queue using Array Implementation)


Prerequisite – Queues
Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle
and the last position is connected back to the first position to make a circle. It is also called ‘Ring Buffer’.

In a normal Queue, we can insert elements until queue becomes full. But once queue becomes full, we cannot insert the
next element even if there is a space in front of queue.

Operations on Circular Queue:

 Front: Get the front item from queue.


 Rear: Get the last item from queue.
 enQueue(value) This function is used to insert an element into the circular queue. In a circular queue, the new element
is always inserted at Rear position.
Steps:

1. Check whether queue is Full – Check ((rear == MAX-1 && front == 0) || ((rear+1)%MAX == front)).
2. if it is full then display Queue is full. If queue is not full then
check if rear==-1 and front ==-1 then set rear = 0, front=0, cq[rear]=element;
else
set rear=(rear+1)%MAX and insert element cq[rear]=element;
.
 deQueue() This function is used to delete an element from the circular queue. In a circular queue, the element is
always deleted from front position.
Steps:

1. Check whether queue is Empty means check (front==-1).


2. If it is empty then display Queue is empty. If queue is not empty then step 3
3. Check if (front==rear) if it is true then set front=rear= -1 after retrun cq[front];
else
set temp=cq[front], front=(front+1)%MAX return element temp;.
Applications:
1. Memory Management: The unused memory locations in the case of ordinary queues can be utilized in circular
queues.
2. Traffic system: In computer controlled traffic system, circular queues are used to switch on the traffic lights one by one
repeatedly as per the time set.
3. CPU Scheduling: Operating systems often maintain a queue of processes that are ready to execute or that are waiting
for a particular event to occur.

Program for Circular Queue

Execution:

Infix expression to Postfix expression conversion:

Infix to Postfix using stack


Prerequisite :-
Infix expression:The expression of the form a op b. When an operator is in-between every pair of operands.
Postfix expression:The expression of the form a b op. When an operator is followed for every pair of operands.
Why postfix representation of the expression?
The compiler scans the expression either from left to right or from right to left.
Consider the below expression: a op1 b op2 c op3 d
If op1 = +, op2 = *, op3 = +
The compiler first scans the expression to evaluate the expression b * c, then again scan the expression to add a to it.
The result is then added to d after another scan.
The repeated scanning makes it very in-efficient. It is better to convert the expression to postfix(or prefix) form
before evaluation.
The corresponding expression in postfix form is: abc*+d+. The postfix expressions can be evaluated easily using a
stack. We will cover postfix expression evaluation in a separate post.
Algorithm
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
…..3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the
stack is empty or the stack contains a ‘(‘ ), push it.
…..3.2 Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the
scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while
popping then stop there and push the scanned operator in the stack.)
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop the stack and and output it until a ‘(‘ is encountered, and discard both the
parenthesis.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty.

8. Print the output


Let’s take an example to better understand the algorithm

Infix Expression: A+ (B*C-(D/E^F)*G)*H, where ^ is an exponential operator.


Resultant Postfix Expression: ABC*DEF^/G*-H*+

Program for infix to postfix expression


Execution

Postfix evaluation:

Stack | Set 4 (Evaluation of Postfix Expression)


The Postfix notation is used to represent algebraic expressions. The expressions written in postfix form are evaluated faster
compared to infix notation as parenthesis are not required in postfix. We have discussed infix to postfix conversion. In this
post, evaluation of postfix expressions is discussed.
Following is algorithm for evaluation postfix expressions.
1) Create a stack to store operands (or values).
2) Scan the given expression and do following for every scanned element.
…..a) If the element is a number, push it into the stack
…..b) If the element is a operator, pop operands for the operator from stack. Evaluate the operator and push the result back
to the stack
3) When the expression is ended, the number in the stack is the final answer

Example:
Let the given expression be “2 3 1 * + 9 -“. We scan all elements one by one.
1) Scan ‘2’, it’s a number, so push it to stack. Stack contains ‘2’
2) Scan ‘3’, again a number, push it to stack, stack now contains ‘2 3’ (from bottom to top)
3) Scan ‘1’, again a number, push it to stack, stack now contains ‘2 3 1’
4) Scan ‘*’, it’s an operator, pop two operands from stack, apply the * operator on operands, we get 3*1
which results in 3. We push the result ‘3’ to stack. Stack now becomes ‘2 3’.
5) Scan ‘+’, it’s an operator, pop two operands from stack, apply the + operator on operands, we get 3 +
2 which results in 5. We push the result ‘5’ to stack. Stack now becomes ‘5’.
6) Scan ‘9’, it’s a number, we push it to the stack. Stack now becomes ‘5 9’.
7) Scan ‘-‘, it’s an operator, pop two operands from stack, apply the – operator on operands, we get 5 –
9 which results in -4. We push the result ‘-4’ to stack. Stack now becomes ‘-4’.
8) There are no more elements to scan, we return the top element from stack (which is the only element
left in stack).

Program for Postfix evaluation:

Execution:

S-ar putea să vă placă și