Data Structure All Notes
Data Structure All Notes
Structure
CONTENTS
1.1 Basic Terminology
1. Elementary data structure organization
2. Classification of data structure
1.2 Operations on data structures
1.3 Different Approaches to designing an algorithm
1. Top-Down approach
2. Bottom-up approach
1.4 Complexity
1. Time complexity
2. Space complexity
1.5 Big ‘O’ Notation
Hours: 6
Marks: 8
1. Introduction to Data Structure
Figure 1.1
Anuradha Bhatia 2
1. Introduction to Data Structure
Anuradha Bhatia 3
1. Introduction to Data Structure
1.4 Complexity
1. Time complexity
(Question: Explain time complexity of an algorithm with operation
count and step count- 4 Marks)
Time Complexity is divided in to THREE Types.
i. Best Case Time Complexity: Efficiency of an algorithm for an input of size
N for which the algorithm takes the smallest amount of time.
ii. Average Case Time Complexity: It gives the expected value of T(n).
Average case is used when worst case and best case doesn’t gives any
necessary information about algorithm’s behavior, then the algorithm’s
efficiency is calculated on Random input.
iii. Worst Case Time Complexity: efficiency of an algorithm for an input of size
N for which the algorithm takes the longest amount of time.
Figure 1.2
Anuradha Bhatia 4
1. Introduction to Data Structure
Example
Figure 1.3
Anuradha Bhatia 5
1. Introduction to Data Structure
Figure 1.4
iv. In the above program there are no instance characteristics and the space
needed by x, y, z and sum is independent of instance characteristics. The
space for each integer variable is 2. We have 4 integer variables and space
needed by x, y, z and sum are 4 * 2 = 8 bytes.
S (p) = Cp + Sp
S (p) = 8 + 0
S (p) = 8
Anuradha Bhatia 6
1. Introduction to Data Structure
Figure 1.5
Figure 1.6
Anuradha Bhatia 7
1. Introduction to Data Structure
Figure 1.7
Anuradha Bhatia 8
Sorting & Searching
CONTENTS
2.1 Sorting Techniques
1. Introduction
2. Selection sort
3. Insertion sort
4. Bubble sort
5. Merge sort
6. Radix sort ( Only algorithm )
7. Shell sort ( Only algorithm )
8. Quick sort ( Only algorithm )
2.2 Searching
1. Linear search
2. Binary search
Hours: 10
Marks: 16
2 Sorting and Searching
Anuradha Bhatia 2
2 Sorting and Searching
2. Selection Sort
(Question: Explain the concept of selection sort with program, advantages
and its disadvantages – 8 Marks)
i. The list is divided into two sub lists, sorted and unsorted, which are
divided by an imaginary wall.
ii. We find the smallest i.e the minimum element from the unsorted sub
list and swap it with the element at the beginning of the unsorted data.
iii. After each selection and swapping, the imaginary wall between the
two sub lists move one element ahead, increasing the number of
sorted elements and decreasing the number of unsorted ones.
iv. Each time we move one element from the unsorted sub list to the
sorted sub list, we say that we have completed a sort pass.
v. A list of n elements requires n-1 passes to completely rearrange the
data.
Original List
After Pass 1
After Pass 2
After Pass 3
After Pass 4
After Pass 5
Anuradha Bhatia 3
2 Sorting and Searching
Disadvantages
i. The primary disadvantage of the selection sort is its poor efficiency when
dealing with a huge list of items.
ii. Its performance is easily influenced by the initial ordering of the items
before the sorting process.
WAP to sort the elements using selection sort
#include <stdio.h>
void main()
{
int array[100], n, i, j, min, swap;
Anuradha Bhatia 4
2 Sorting and Searching
3. Insertion Sort
(Question: Explain the concept of insertion sort with program, advantages
and its disadvantages – 8 Marks)
i. It always maintains two zones in the array to be sorted: sorted and
unsorted.
ii. At the beginning the sorted zone consist of one element (the first
element of array that we are sorting).
iii. On each step the algorithms expand the sorted zone by one element
inserting the first element from the unsorted zone in the proper place
in the sorted zone and shifting all larger elements one slot down.
Advantages
i. The insertion sorts repeatedly scans the list of items, each time
inserting the item in the unordered sequence into its correct position.
ii. The main advantage of the insertion sort is its simplicity. It also exhibits
a good performance when dealing with a small list. The insertion sort
is an in-place sorting algorithm so the space requirement is minimal.
Disadvantage
i. The disadvantage of the insertion sort is that it does not perform as
well as other, better sorting algorithms.
ii. With n-squared steps required for every n element to be sorted, the
insertion sort does not deal well with a huge list.
iii. Therefore, the insertion sort is particularly useful only when sorting a
list of few items.
Anuradha Bhatia 5
2 Sorting and Searching
Anuradha Bhatia 6
2 Sorting and Searching
4. Bubble Sort
(Question: Explain the concept of bubble sort with program, advantages
and its disadvantages – 8 Marks)
i. Bubble sort algorithms cycle through a list, analyzing pairs of elements
from left to right, or beginning to end.
ii. If the leftmost element in the pair is less than the rightmost element,
the pair will remain in that order. If the rightmost element is less than
the leftmost element, then the two elements will be switched.
iii. This cycle repeats from beginning to end until a pass in which no switch
occurs.
Advantages
i. The bubble sort requires very little memory other than that which the
array or list itself occupies.
ii. The bubble sort is comprised of relatively few lines of code.
iii. With a best-case running time of O(n), the bubble sort is good for
testing whether or not a list is sorted or not. Other sorting methods
often cycle through their whole sorting sequence, which often have
running times of O(n^2) or O(n log n) for this task.
iv. The same applies for data sets that have only a few items that need to
be swapped a few times.
Disadvantages
i. The main disadvantage of the bubble sort method is the time it
requires.
ii. With a running time of O (n^2), it is highly inefficient for large data sets.
Anuradha Bhatia 7
2 Sorting and Searching
#include <stdio.h>
int main()
{
int array[100], n, i, j, temp;
return 0;
}
Anuradha Bhatia 8
2 Sorting and Searching
5. Merge Sort
(Question: Explain the concept of merge sort with program, advantages
and its disadvantages – 8 Marks)
i. It follows the fundamental of dividing the elements and sorting, as
sorting is easier in smaller bits of elements.
ii. If the sub list is 1 in length, then the sub list is sorted.
iii. If the list is more than one in length, then divide the unsorted list into
roughly two parts.
iv. Keep dividing the sub lists until each one is only 1 item in length.
v. Now merge the sub-lists back into a list twice their size, at the same
time sorting each items into order.
vi. Keep merging the sub list until the list is complete once again.
Advantage
i. Good for sorting slow-access data.
ii. It is excellent for sorting data that are normally accessed sequentially.
Disadvantage
i. If the list is N long, then it takes 2*N memory space to sort the
elements.
ii. For large data its time and space complexity is of the order of nlogn.
WAP to sort the elements in the array using merge sort.
#include<stdio.h>
#define MAX 50
int main(){
int merge[MAX],i,n;
Anuradha Bhatia 9
2 Sorting and Searching
return 0;
}
int mid;
if(low<high){
mid=(low+high)/2;
partition(arr,low,mid);
partition(arr,mid+1,high);
mergeSort(arr,low,mid,high);
}
}
void mergeSort(int arr[],int low,int mid,int high){
int i,m,k,l,temp[MAX];
l=low;
i=low;
m=mid+1;
while((l<=mid)&&(m<=high)){
if(arr[l]<=arr[m]){
temp[i]=arr[l];
l++;
}
else{
temp[i]=arr[m];
m++;
}
i++;
}
Anuradha Bhatia 10
2 Sorting and Searching
if(l>mid){
for(k=m;k<=high;k++){
temp[i]=arr[k];
i++;
}
}
else{
for(k=l;k<=mid;k++){
temp[i]=arr[k];
i++;
}
}
for(k=low;k<=high;k++){
arr[k]=temp[k];
}
}
Anuradha Bhatia 11
2 Sorting and Searching
6. Radix Sort
(Question: Explain the concept of radix sort the given series of numbers – 8
Marks)
Bucket 0 1 2 3 4 5 6 7 8 9
Content 1 - - 64 25 36 - - 9
81 4 16 49
v. This sort is implemented for the good functionality for a three bit
number.
vi. After the Pass 1 print the list and continue with the same on the middle
bit and put in the respective buckets.
Bucket 0 1 2 3 4 5 6 7 8 9
Content 01 16 25 36 49 64 81
04
09
Figure 5: Radix Sort Pass 2
Anuradha Bhatia 12
2 Sorting and Searching
7. Shell Sort
(Question: Explain the concept of shell sort the given series of numbers – 8
Marks)
i. The shell sort, sometimes called the “diminishing increment sort,”
improves on the insertion sort by breaking the original list into a
number of smaller sub lists, each of which is sorted using an insertion
sort.
ii. The unique way that these sub lists are chosen is the key to the shell
sort.
iii. Instead of breaking the list into subsists of contiguous items, the shell
sort uses an increment i, sometimes called the gap, to create a sub list
by choosing all items that are i items apart.
iv. This can be seen in Figure 6. This list has nine items.
v. If we use an increment of three, there are three sub lists, each of which
can be sorted by an insertion sort.
vi. After completing these sorts, we get the list shown in Figure 7.
vii. Although this list is not completely sorted, something very interesting
has happened. By sorting the sub lists, we have moved the items closer
to where they actually belong.
Anuradha Bhatia 13
2 Sorting and Searching
viii. Figure 8 shows a final insertion sort using an increment of one; in other
words, a standard insertion sort.
ix. Note that by performing the earlier sub list sorts, we have now reduced
the total number of shifting operations necessary to put the list in its
final order.
x. For this case, we need only four more shifts to complete the process.
Anuradha Bhatia 14
2 Sorting and Searching
8. Quick Sort
(Question: Explain the concept of quick sort the given series of numbers – 8
Marks)
i. The quicksort algorithm partitions an array of data into items that are
less than the pivot and those that are greater than or equal to the pivot
item.
ii. The first step is to create the partitions, in which a random pivot item
is created, and the partition algorithm is applied to the array of items.
iii. This initial step is the most difficult part of the Quicksort algorithm.
Advantages
i. The efficient average case compared to any aforementioned sort
algorithm, as well as the elegant recursive definition, and the
popularity due to its high efficiency.
ii. The quick sort produces the most effective and widely used method of
sorting a list of any item size.
Disadvantages
i. The difficulty of implementing the partitioning algorithm and the
average efficiency for the worst case scenario, which is not offset by
the difficult implementation.
ii. Quicksort works by "partitioning" the array to be sorted, then
recursively sorting each partition. Here is the pseudocode.
Anuradha Bhatia 15
2 Sorting and Searching
Anuradha Bhatia 16
2 Sorting and Searching
2.2 Searching
1. Linear Search
(Question: Explain the concept of linear the given series of numbers – 8
Marks)
Anuradha Bhatia 17
2 Sorting and Searching
if(c==0)
printf("The number is not in the list");
else
printf("The number is found");
return 0;
}
WAP to find the element present in the array and also print its location.
#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter the number of elements in array\n");
scanf("%d",&n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* if required element found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d is not present in array.\n", search);
return 0;
}
Anuradha Bhatia 18
2 Sorting and Searching
2. Binary Search
(Question: Explain the concept of binary search for the given series of
numbers – 8 Marks)
i.
A binary search divides a range of values into halves, and continues to
narrow down the field of search until the unknown value is found.
ii. It is the classic example of a "divide and conquer" algorithm.
WAP to search the element in the array using binary search
#include <stdio.h>
void main ()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
Anuradha Bhatia 19
Stacks
CONTENTS
3.1 Introduction
1. Stack as an abstract data type
2. Representation of a Stack as an array
3.2Applications of Stack
Hours: 12
Marks: 18
3. Stack
Anuradha Bhatia 2
3. Stack
iv. This means that their contexts are stored in what looks like a line
(although vertically) as shown in Figure 1.
v. This linear property, however, is not sufficient to discriminate a stack
from other linear data structures.
vi. For example, an array is a sort of linear data structure. However, you
can access any element in an array--not true for a stack, since you can
only deal with the element at its top.
vii. One of the distinguishing characteristics of a stack, and the thing that
makes it useful, is the order in which elements come out of a stack.
Stack empty
Stack
d) Now let's remove an item, letter = Pop(stack), giving:
Stack
Anuradha Bhatia 3
3. Stack
f) In the last step pop out all the elements from the stack. The final
printed stack will be B, C, A
3.2 Application of Stacks
1. Reversing the list
(Question: WAP to reverse the number using stack- 4 Marks)
i. The application of the stack is it prints any given series of numbers
whether sorted or unsorted in reverse order.
ii. As the stack follows Last In First Order (LIFO), it gives the series of
number in reverse order.
iii. Given below is the program to print the stack.
WAP to PUSH and POP the elements on to the stack, without using functions
#include<stdio.h>
void main()
{
int stack[5], top = -1;
while (top <5)
{
top++;
printf (“\nenter the element for the stack”);
scanf (“%d”, &stack[top]);
}
while (top!=0)
{
printf(“\nthe popped element is %d”, st[top]);
top = top -1;
}
}
OUTPUT:
enter the element for the stack10
enter the element for the stack20
enter the element for the stack30
enter the element for the stack40
enter the element for the stack50
the popped element is50
the popped element is40
the popped element is30
the popped element is20
the popped element is10
Anuradha Bhatia 4
3. Stack
2. Polish Notation
(Question: Explain the concept of polish notation- 4 Marks)
i. Infix, Postfix and Prefix notations are three different but equivalent
ways of writing expressions known as Polish notation.
ii. It is easiest to demonstrate the differences by looking at examples
of operators that take two operands.
Infix notation: X + Y
Postfix notation (also known as "Reverse Polish notation"): X Y +
Prefix notation (also known as "Polish notation"): + X Y
iii. Operators are written in-between their operands.
iv. An expression such as A * (B + C) / D is usually taken to mean by
multiplication first, then followed by division and then +.
Examples: A * B + C / D ( ( A * B ) + ( C / D ) )
push(char elem)
{ /* Function for PUSH operation */
s[++top]=elem;
}
char pop()
{ /* Function for POP operation */
Anuradha Bhatia 5
3. Stack
return(s[top--]);
}
int pr(char elem)
{ /* Function for precedence */
switch(elem)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
}
}
main()
{ /* Main Program */
char infx[50],pofx[50],ch,elem;
int i=0,k=0;
printf("\n\nRead the Infix Expression ? ");
scanf("%s",infx);
push('#');
while( (ch=infx[i++]) != '\0')
{
if( ch == '(') push(ch);
else
if(isalnum(ch)) pofx[k++]=ch;
else
if( ch == ')')
{
while( s[top] != '(')
pofx[k++]=pop();
elem=pop(); /* Remove ( */
}
else
{ /* Operator */
while( pr(s[top]) >= pr(ch) )
pofx[k++]=pop();
push(ch);
}
}
while( s[top] != '#') /* Pop from stack till empty */
pofx[k++]=pop();
pofx[k]='\0'; /* Make pofx as valid string */
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n",infx,pofx);
}
Anuradha Bhatia 6
3. Stack
OUTPUT
Read the Infix Expression? A+B*C
Given Infix Expn: A+B*C Postfix Expn: ABC*+
v. The next element is an operator (*), so we pop out the top two
number from the stack and perform * on the two numbers.
Anuradha Bhatia 7
3. Stack
Anuradha Bhatia 8
3. Stack
Anuradha Bhatia 9
3. Stack
push(ch);
else if (isalnum(ch))
pofx[k++] = ch;
else if (ch == ')') {
while (s[top] != '(')
pofx[k++] = pop();
elem = pop(); /* Remove ( */
} else { /* Operator */
while (pr(s[top]) >= pr(ch))
pofx[k++] = pop();
push(ch);
}
}
while (s[top] != '#') /* Pop from stack till empty */
pofx[k++] = pop();
pofx[k] = '\0'; /* Make pofx as valid string */
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n", infx, pofx);
Anuradha Bhatia 10
3. Stack
push(char elem)
{ /* Function for PUSH operation */
s[++top]=elem;
}
char pop()
{ /* Function for POP operation */
return(s[top--]);
}
main()
{ /* Main Program */
char infx[50],prfx[50],ch,elem;
int i=0,k=0;
Anuradha Bhatia 11
3. Stack
Example of conversions
Infix Postfix Prefix Notes
A * B + C / D A B * C D / + + * A B / C D multiply A and B, divide C by
D, add the results
A * (B + C) / D A B C + * D / / * A + B C D add B and C, multiply by A,
divide by D
A * (B + C / D) A B C D / + * * A + B / C D divide C by D, add B, multiply
by A
Anuradha Bhatia 12
3. Stack
Example 1: A * B + C becomes A B * C +
1 A A
2 * * A
3 B * AB
4 + + A B * {pop and print the '*' before pushing
the '+'}
5 C + AB*C
6 AB*C+
Example 2: A + B * C becomes A B C * +
Anuradha Bhatia 13
3. Stack
Example 3: A * (B + C) becomes A B C + *
Example 4. A - B + C becomes A B - C +
iii. In line 4, the '-' will be popped and printed before the '+' is pushed onto
the stack.
iv. Both operators have the same precedence level, so left to right association
tells us to do the first one found before the second.
Anuradha Bhatia 14
3. Stack
5. A * B ^ C + D becomes A B C ^ * D +
ii. When the '+' is encountered in line 6, it is first compared to the '^' on
top of the stack.
iii. Since it has lower precedence, the '^' is popped and printed.
iv. But instead of pushing the '+' sign onto the stack now, we must
compare it with the new top of the stack, the '*'.
v. Since the operator also has higher precedence than the '+', it also must
be popped and printed. Now the stack is empty, so the '+' can be
pushed onto the stack.
6. A * (B + C * D) + E becomes A B C D * + * E +
Anuradha Bhatia 15
3. Stack
Anuradha Bhatia 16
3. Stack
Example: A+B*C
Step 1: Reverse the string as C*B+A
Step 2:
Anuradha Bhatia 17
3. Stack
reverse(infix);
for (i=0;i<strlen(infix);i++) {
symbol=infix[i];
if (isOperator(symbol)==0) {
prefix[j]=symbol;
j++;
} else {
if (symbol==')') {
push(symbol);
} else if(symbol == '(') {
while (stack[top]!=')') {
prefix[j]=pop();
j++;
}
pop();
} else {
if (prcd(stack[top])<=prcd(symbol)) {
push(symbol);
} else {
while(prcd(stack[top])>=prcd(symbol)) {
prefix[j]=pop();
j++;
}
push(symbol);
}
//end for else
}
}
//end for else
}
//end for for
while (stack[top]!='#') {
prefix[j]=pop();
j++;
}
prefix[j]='\0';
}
////--------------------------------------------------------
void reverse(char array[30]) // for reverse of the given expression {
Anuradha Bhatia 18
3. Stack
int i,j;
char temp[100];
for (i=strlen(array)-1,j=0;i+1!=0;--i,++j) {
temp[j]=array[i];
}
temp[j]='\0';
strcpy(array,temp);
return array;
}
//--------------------------------
char pop() {
char a;
a=stack[top];
top--;
return a;
}
//----------------------------------
void push(char symbol) {
top++;
stack[top]=symbol;
}
//------------------------------------------
int prcd(symbol) // returns the value that helps in the precedence {
switch(symbol) {
case '+':
case '-':
return 2;
break;
case '*':
case '/':
return 4;
break;
case '$':
case '^':
return 6;
break;
case '#':
case '(':
case ')':
Anuradha Bhatia 19
3. Stack
return 1;
break;
}
}
//-------------------------------------------------
int isOperator(char symbol) {
switch(symbol) {
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '&':
case '(':
case ')':
return 1;
break;
default:
return 0;
// returns 0 if the symbol is other than given above
}
}
Anuradha Bhatia 20
Queues
CONTENTS
4.1 Introduction
1. Queues as an abstract data type
2. Representation of a Queue as an array
4.2 Types of Queue
1. Circular Queue
2. Double Ended Queue
3. Priority Queue
4.3 Applications of Queue
Hours: 8
Marks: 12
Anuradha Bhatia 1
4. Queue
Operations on Queue
i. createQueue() :Create an empty queue
ii. destroyQueue(): Destroy a queue
iii. isEmpty():Boolean: Determine whether a queue is empty
iv. enqueue(in newItem:QueueItemType) throw QueueException: Inserts a
new item at the end of the queue (at the rear of the queue)
v. dequeue() throw QueueException
dequeue(out queueFront:QueueItemType) throw QueueException
Removes (and returns) the element at the front of the queue
Remove the item that was added earliest
vi. getFront(out queueFront:QueueItemType) throw QueueException:
Retrieve the item that was added earliest (without removing).
i. With queues two integer indexes are required, one giving the position of
the front element of the queue in the array, the other giving the position
Anuradha Bhatia 2
4. Queue
of the back element, or rather in a similar way to stacks, the position after
the back element.
ii. We add the elements from rear, and remove the elements from the front
as shown in the Figure.
Front Rear
iii. In queue as we delete one data element, the front is incremented by one.
iv. We delete the elements from the end, known as the rear of the queue.
v. The disadvantage of using the queue is as we delete the elements, the
front moves ahead, even though the queue is empty we still cannot add
the elements in the queue.
(Question: WAP to perform add and delete elements from the queue -
6 marks)
qu[rear] = item;
Anuradha Bhatia 3
4. Queue
}
}
void delq()
{
printf(" The removed item is %d", qu[front]);
front= front + 1;
}
void main()
{
int ch = 1,ans =0,ele,temp;
clrscr();
do
{
printf("\n 1: Add the element in the queue");
printf("\n 2: Delete the element from the queue");
printf("\n 3: Display the queue");
printf("\n 4: Exit");
printf("\n Enter your choice ");
scanf("%d",&ch);
switch(ch)
{
case 1: { if (rear<=5)
{
printf("Enter the element to be added ");
scanf("%d",&ele);
addq(ele);
break;
}
else
{
printf("Queue Full");
break;
}
}
case 2: {
Anuradha Bhatia 4
4. Queue
delq();
break;
}
case 3: { temp = front;
while (front <= rear)
{
printf("\n The element of the queue are %d", qu[front]);
front++;
}
front = temp;
break;
}
case 4: {
exit();
break;
}
}
printf(" \n Do you want to continue(1 to continue , 0 to exit) ");
scanf("%d", &ans);
}while(ans != 0);
}
OUTPUT
Anuradha Bhatia 5
4. Queue
Anuradha Bhatia 6
4. Queue
10 20 30 40 50
Anuradha Bhatia 7
4. Queue
Step 1. Start
Step 2. if (front == (rear+1)%max)
Print error “circular queue overflow “
Step 3. Else
{ rear = (rear+1)%max
Q[rear] = element;
If (front == -1 ) f = 0;
}
Step 4. Stop
Step 1. Start
Step 2. if ((front == rear) && (rear == -1))
Print error “circular queue underflow “
step 3. else
{ element = Q[front]
If (front == rear) front=rear = -1
Else
Front = (front + 1) % max
Step 4. Stop
Anuradha Bhatia 8
4. Queue
WAP to insert, delete and display the elements of the circular queue.
#include<stdio.h>
#define SIZE 5
void insert();
void delet();
void display();
int queue[SIZE], rear=-1, front=-1, item;
main()
{
int ch;
do
{
printf("\n\n1. \tInsert\n2. \tDelete\n3. \tDisplay\n4. \tExit\n");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
delet();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\n\nInvalid choice. Please try again... \n");
}
} while(1);
getch();
}
void insert()
{
if((front==0 && rear==SIZE-1) || (front==rear+1))
printf("\n\nQueue is full.");
Anuradha Bhatia 9
4. Queue
else
{
printf("\n\nEnter ITEM: ");
scanf("%d", &item);
if(rear == -1)
{
rear = 0;
front = 0;
}
else if(rear == SIZE-1)
rear = 0;
else
rear++;
queue[rear] = item;
printf("\n\nItem inserted: %d\n", item);
}
}
void delet()
{
if(front == -1)
printf("\n\nQueue is empty. \n");
else
{
item = queue[front];
if(front == rear)
{
front = -1;
rear = -1;
}
Anuradha Bhatia 10
4. Queue
void display()
{
int i;
if((front == -1) || (front==rear+1))
printf("\n\nQueue is empty. \n");
else
{ printf("\n\n");
for(i=front; i<=rear; i++)
printf("\t%d",queue[i]);
}
}
Anuradha Bhatia 11
4. Queue
Anuradha Bhatia 12
4. Queue
Anuradha Bhatia 13
4. Queue
WAP to add, delete, and display the elements in a double ended queue.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
int q[MAX],front=0,rear=0;
void add_rear();
void add_front();
void delete_rear();
void delete_front();
void display();
void main()
{
int ch;
clrscr();
do
{
clrscr();
printf("\n DQueue Menu");
printf("\n--------------");
printf("\n 1. Add Rear");
printf("\n 2. Add Front");
printf("\n 3. Delete Rear");
printf("\n 4. Delete Front");
printf("\n 5. Display");
printf("\n 6. Exit");
printf("\n Enter your choice:-");
scanf("%d",&ch);
Anuradha Bhatia 14
4. Queue
switch(ch)
{
case 1:
{
add_rear();
printf("\n Queue after insert at rear");
display();
break;
}
case 2:
{
add_front();
printf("\n Queue after insert at front");
display();
break;
}
case 3:
{
delete_rear();
printf("\n Queue after delete at rear");
display();
break;
}
case 4:
{
delete_front();
printf("\n Queue after delete at front");
display();
break;
}
case 5:
{
display();
break;
}
Anuradha Bhatia 15
4. Queue
case 6:
{
exit(0);
break;
}
default:
{
printf("\n Wrong Choice\n");
}
}
} while(ch!=6);
}
void add_rear()
{
int no;
printf("\n Enter value to insert : ");
scanf("%d",&no);
if(rear==MAX)
{
printf("\n Queue is Overflow");
return;
}
else
{
rear++;
q[rear]=no;
if(rear==0)
rear=1;
if(front==0)
front=1;
}
}
Anuradha Bhatia 16
4. Queue
void add_front()
{
int no;
printf("\n Enter value to insert:-");
scanf("%d",&no);
if(front<=1)
{
printf("\n Cannot add value at front end");
return;
}
else
{
front--;
q[front]=no;
}
}
void delete_front()
{
int no;
if(front==0)
{
printf("\n Queue is Underflow\n");
return;
}
else
{
no=q[front];
printf("\n Deleted element is %d\n",no);
if(front==rear)
{
front=0;
rear=0;
}
else
{
front++;
}
}
}
Anuradha Bhatia 17
4. Queue
void delete_rear()
{
int no;
if(rear==0)
{
printf("\n Cannot delete value at rear end\n");
return;
}
else
{
no=q[rear];
if(front==rear)
{
front=0;
rear=0;
}
else
{
rear--;
printf("\n Deleted element is %d\n",no);
}
}
}
void display()
{ int i;
if(front==0)
{
printf("\n Queue is Underflow\n");
return;
}
else
{
printf("\n Output");
for(i=front;i<=rear;i++)
{ printf("\n %d",q[i]);
}
}
}
Anuradha Bhatia 18
4. Queue
3. Priority Queue
(Question: Explain the concept of priority queue - 4 marks)
WAP to insert and delete elements from priority queue using arrays
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
void insert_by_priority(int);
void delete_by_priority(int);
void create();
void check(int);
void display_pqueue();
int pri_que[MAX];
int front, rear;
void main()
{
int n, ch;
Anuradha Bhatia 19
4. Queue
create();
while (1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter value to be inserted : ");
scanf("%d",&n);
insert_by_priority(n);
break;
case 2:
printf("\nEnter value to delete : ");
scanf("%d",&n);
delete_by_priority(n);
break;
case 3:
display_pqueue();
break;
case 4:
exit(0);
default:
printf("\nChoice is incorrect, Enter a correct choice");
}
}
}
Anuradha Bhatia 20
4. Queue
Anuradha Bhatia 21
4. Queue
pri_que[i] = data;
return;
}
}
pri_que[i] = data;
}
pri_que[i] = -99;
rear--;
if (rear == -1)
front = -1;
return;
}
}
printf("\n%d not found in queue to delete", data);
}
Anuradha Bhatia 22
4. Queue
front = 0;
}
Anuradha Bhatia 23
4. Queue
4.3 Applications
i. When a resource is shared among multiple consumers. Examples
include CPU scheduling, Disk Scheduling.
ii. When data is transferred asynchronously (data not necessarily
received at same rate as sent) between two processes. Examples
include IO Buffers, pipes, file IO, etc.
Anuradha Bhatia 24
Link List
CONTENTS
5.1 Introduction
1. Terminologies: node, Address, Pointer,
Information, Next, Null Pointer, Empty list etc.
5.2 Type of lists
1. Linear list
2. Circular list
3. Doubly list
5.3 Operations on a singly linked list ( only algorithm)
1. Traversing a singly linked list
2. Searching a linked list
3. Inserting a new node in a linked list
4. Deleting a node from a linked list
Hours: 8
Marks: 12
Anuradha Bhatia 1
5. Link List
Data Link
Node
b. Address: Stores the address of the next node of the link list.
c. Pointer: A data type used to point to the address of the next node.
d. Information: The data stored in the data field of the link list
structure.
e. Next: The link which points to the next node of the link list
f. Null Pointer: Signifies the end of link list, when the next or the
link pointer points to NULL
g. Empty list: Signifies no data in the link list.
Anuradha Bhatia 2
5. Link List
No Element Explanation
int main()
{
struct node *root;
root = (struct node *) malloc( sizeof(struct node) );
root->next = NULL;
root->data = 18;
}
Anuradha Bhatia 3
5. Link List
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
int main()
{
struct node *root;
struct node *temp;
root = malloc( sizeof(struct node) );
root->next = NULL;
root->x = 18;
temp = root;
if ( temp != NULL )
{
while ( temp->next != NULL)
{
temp = temp->next;
}
}
temp->next = malloc( sizeof(struct node) );
temp = temp->next;
if ( temp == 0 )
{
printf( "Out of memory" );
return 0;
}
/* initialize the new memory */
temp->next = NULL;
temp->data = 22;
return 0;
}
Anuradha Bhatia 4
5. Link List
temp = root;
if ( temp != 0 ) { /* Makes sure there is a place to start */
while ( temp->next != NULL )
{
printf( "%d\n", temp->data);
temp = temp->next;
}
printf( "%d\n", temp->x );
}
Advantages
1. The advantage of a singly linked list is its ability to expand to accept
virtually unlimited number of nodes in a fragmented memory
environment. Linked lists are a dynamic data structure, allocating the
needed memory while the program is running.
2. Insertion and deletion node operations are easily implemented in a linked
list.
3. Linear data structures such as stacks and queues are easily executed with
a linked list.
4. They can reduce access time and may expand in real time without memory
overhead.
Disadvantages
1. The disadvantage is its speed. Operations in a singly-linked list are slow as
it uses sequential search to locate a node.
2. They have a tendency to use more memory due to pointers requiring extra
storage space.
3. Nodes in a linked list must be read in order from the beginning as linked
lists are inherently sequential access.
4. Nodes are stored in contiguously, greatly increasing the time required to
access individual elements within the list.
5. Difficulties arise in linked lists when it comes to reverse traversing. For
instance, singly linked lists are cumbersome to navigate backwards and
Anuradha Bhatia 5
5. Link List
while doubly linked lists are somewhat easier to read, memory is wasted
in allocating space for a back pointer.
WAP to add, delete, display and search the element in the link list
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
void insert(node *pointer, int data)
{
while(pointer->next!=NULL)
{
pointer = pointer -> next;
}
pointer->next = (node *)malloc(sizeof(node));
pointer = pointer->next;
pointer->data = data;
pointer->next = NULL;
}
int search(node *pointer, int key)
{
pointer = pointer -> next; //First node is dummy node.
while(pointer!=NULL)
{
if(pointer->data == key) //key is found.
{
return 1;
}
pointer = pointer -> next;//Search in the next node.
}
return 0;
}
Anuradha Bhatia 6
5. Link List
Anuradha Bhatia 7
5. Link List
while(1)
{
int query;
scanf("%d",&query);
if(query==1)
{
int data;
scanf("%d",&data);
insert(start,data);
}
else if(query==2)
{
int data;
scanf("%d",&data);
delete(start,data);
}
else if(query==3)
{
printf("The list is ");
print(start->next);
printf("\n");
}
else if(query==4)
{
int data;
scanf("%d",&data);
int status = seach(start,data);
if(status)
{
printf("Element Found\n");
}
else
{
printf("Element Not Found\n");
}
}
}
}
Anuradha Bhatia 8
5. Link List
2. Circular list
(Question: explain the concept of circular list- 4 Marks)
a. Circular Linked List is divided into 2 Categories.
Singly Circular Linked List
Doubly Circular Linked List
b. In Circular Linked List Address field of Last node contain address
of “First Node“.
c. In short First Node and Last Nodes are adjacent.
d. Linked List is made circular by linking first and last node, so it
looks like circular chain [shown in following diagram].
e. Two way access is possible only if we are using “Doubly Circular
Linked List” Sequential movement is possible, No direct access
is allowed.
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
void insert(node *pointer, int data)
{
node *start = pointer;
while(pointer->next!=start)
{
pointer = pointer -> next;
}
Anuradha Bhatia 9
5. Link List
Anuradha Bhatia 10
5. Link List
Anuradha Bhatia 11
5. Link List
else if(query==3)
{
printf("The list is ");
print(start,start->next);
printf("\n");
}
else if(query==4)
{
int data;
scanf("%d",&data);
int status = find(start,data);
if(status)
{
printf("Element Found\n");
}
else
{
printf("Element Not Found\n");
}
}
}
}
3. Doubly list
(Question: Explain the concept of doubly link list- 4 Marks)
Anuradha Bhatia 12
5. Link List
void creat()
{
char ch;
do
{
struct node *new_node,*current;
new_node=(struct node *)malloc(sizeof(struct node));
if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
current->next=new_node;
current=new_node;
}
printf("nDo you want to creat another : ");
ch=getche();
}while(ch!='n');
}
Anuradha Bhatia 13
5. Link List
temp = start;
while(temp!=NULL)
{
if(temp->data == num)
return(1); //Found
temp = temp->next;
}
if(flag == 0)
return(0); // Not found
}
Anuradha Bhatia 14
5. Link List
if(new_node == NULL)
printf("nFailed to Allocate Memory");
if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
new_node->next=start;
start=new_node;
}
}
Anuradha Bhatia 15
5. Link List
Anuradha Bhatia 16
5. Link List
if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
temp = start;
for(i=1;i< pos-1;i++)
{
temp = temp->next;
}
temp1=temp->next;
temp->next = new_node;
new_node->next=temp1;
}
}
Anuradha Bhatia 17
5. Link List
temp = start;
start = start->next;
free(temp);
printf("nThe Element deleted Successfully ");
}
Anuradha Bhatia 18
5. Link List
Step 3: Delete temp i.e Previous Starting Node as we have Updated Version of Start Pointer.
free(temp)
Anuradha Bhatia 19
Trees
CONTENTS
6.1 Introduction
1. Terminologies: tree ,degree of a node, degree of a tree, level of a
node, leaf node, Depth / Height of a tree, In-degree & out-
Degree, Directed edge, Path, Ancestor & descendant nodes.
6.2 Type of Trees
1. General tree
2. Binary tree
3. Binary search tree (BST).
6.3 Binary tree traversal ( only algorithm )
1. In order traversal
2. Preorder traversal
3. Post order traversal
4. Expression tree
Hours: 8
Marks: 12
Anuradha Bhatia 1
6. Trees
iv. Ancestor: The predecessor of a node together with all the ancestors of
the predecessor of a node. The root node has no ancestors.
Anuradha Bhatia 2
6. Trees
Anuradha Bhatia 3
6. Trees
Anuradha Bhatia 4
6. Trees
xvii. Height of node: The height of a node is the number of edges on the
longest downward path between that node and a leaf.
xviii. Depth: The depth of a node is the number of edges from the node to
the tree's root node.
xix. Forest: A forest is a set of n ≥ 0 disjoint trees.
Anuradha Bhatia 5
6. Trees
i. It has one designated node, called the root that has no parent.
ii. Every node, except the root, has exactly one parent.
iii. A node may have zero or more children.
iv. There is a unique directed path from the root to each node.
v. In a general tree, there is no limit to the number of children that a node can
have.
vi. They are suitable for:
Hierarchical structure representation, e.g.,
File directory.
Anuradha Bhatia 6
6. Trees
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define SIZE 9
struct treeNode
{
int item;
struct treeNode *left;
struct treeNode *mid;
struct treeNode *right;
}treeNode;
Anuradha Bhatia 7
6. Trees
Anuradha Bhatia 8
6. Trees
{
if (root == NULL){
root = create_node(item);
}
else{
int is_left = 0;
int is_mid = 0;
int is_right = 0;
int r;
treeNode* cursor = root;
treeNode* prev = NULL;
while(cursor != NULL){
r = compare(item,cursor->item);
prev = cursor;
if (r==1){
is_left = 1;
cursor = cursor->left;
}else if(r==2){
is_mid = 1;
cursor = cursor->mid;
}else if(r==3){
is_right = 1;
cursor = cursor->right;
}
}
if(is_left)
prev->left = create_node(item);
Anuradha Bhatia 9
6. Trees
else if(is_mid)
prev->mid = create_node(item);
else if(is_right)
prev->right = create_node(item);
else{
printf("duplicate values are not allowed!");
}
return root;
}
treeNode * search(treeNode *root,const int item,comparer compare)
{
if (root == NULL)
return NULL;
int r;
treeNode* cursor = root;
while (cursor!=NULL){
r=compare(item,cursor->item);
if(r==1)
cursor = cursor->left;
else if(r == 2)
cursor = cursor->mid;
else if(r == 3)
cursor = cursor->right;
}
return cursor;
}
//delete a node
Anuradha Bhatia 10
6. Trees
Anuradha Bhatia 11
6. Trees
root = cursor;
}
}
return root;
}
void dispose(treeNode* root)
{
if(root != NULL)
{
dispose(root->left);
dispose(root->mid);
dispose(root->right);
free(root);
}
}
Anuradha Bhatia 12
6. Trees
if(nd->left != NULL)
printf("(L:%d)",nd->left->item);
if(nd->mid != NULL)
printf("(R:%d)",nd->mid->item);
if(nd->right != NULL)
printf("(R:%d)",nd->right->item);
printf("\n");
display_tree(nd->left);
display_tree(nd->mid);
display_tree(nd->right);
}
int main(void)
{
treeNode* root = NULL;
comparer int_comp = compare;
int a[SIZE] = {8,3,10,1,6,14,4,7,13,15,2,5,20};
int i;
printf("--- C Binary Search Tree ---- \n\n");
printf("Insert: ");
for(i = 0; i < SIZE; i++)
{
printf("%d ",a[i]);
root = insert_node(root,int_comp,a[i]);
}
printf(" into the tree.\n\n");
/* display the tree */
display_tree(root);
Anuradha Bhatia 13
6. Trees
/* remove element */
int r;
do
{
printf("Enter data to remove, (-1 to exit):");
scanf("%d",&r);
if(r == -1)
break;
root = delete_node(root,r,int_comp);
/* display the tree */
if(root != NULL)
display_tree(root);
else
break;
}
while(root != NULL);
/* search for a node */
int key = 0;
treeNode* s;
while(key != -1)
{
printf("Enter item to search (-1 to exit):");
scanf("%d",&key);
s = search(root,key,int_comp);
if(s != NULL)
{
printf("Found it %d",s->item);
Anuradha Bhatia 14
6. Trees
if(s->left != NULL)
printf("(L: %d)",s->left->item);
if(s->mid != NULL)
printf("(R: %d)",s->mid->item);
if(s->right != NULL)
printf("(R: %d)",s->right->item);
printf("\n");
}
else
{
printf("node %d not found\n",key);
}
}
/* remove the whole tree */
dispose(root);
return 0;
}
}
2. Binary tree
(Question: Explain the concept of binary tree- 4 Marks)
i. A complete binary tree is either an empty binary tree or a binary tree in which:
Each level k, k > 0, other than the last level contains the maximum number
of nodes for that level that is 2k.
The last level may or may not contain the maximum number of nodes.
If a slot with a missing node is encountered when scanning the last level in
a left to right direction, then all remaining slots in the level must be empty.
ii. Thus, every full binary tree is a complete binary tree, but the opposite is not true.
iii. Using double ended link list, binary tree is represented as
Anuradha Bhatia 15
6. Trees
Expression Tree
Anuradha Bhatia 16
6. Trees
vii. Binary tree works on the rule that child nodes which are lesser than root
node keep on the left side and child nodes which are greater than root node
keep on the right side.
viii. Same rule is followed in child nodes as well that are itself sub-trees. Like in
above figure, nodes (2, 4, and 6) are on left side of root node (9) and nodes
(12, 15, and 17) are on right side of root node (9).
Anuradha Bhatia 17
6. Trees
Insertion of a key
(Question: Explain how to insert insertion of a key in binary
tree- 4 Marks)
Anuradha Bhatia 18
6. Trees
i. A new key is always inserted at leaf.
ii. We start searching a key from root till we hit a leaf node. Once a leaf
node is found, the new node is added as a child of the leaf node.
100 100
/ \ Insert 40 / \
/ \ / \
10 30 10 30
40
Anuradha Bhatia 19
6. Trees
Anuradha Bhatia 20
6. Trees
i. Visit the root node in between the left and right node (in).
ii. Traverse the left subtree in in-order
iii. Visit the root (we will print it when we visit to show the order of visiting)
iv. Traverse the right subtree in in-order
Anuradha Bhatia 21
6. Trees
}
}
WAP to convert the expression to in order pre order and post order
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
struct BST {
int data;
struct BST *lchild, *rchild;
} node;
void main() {
int choice;
char ans = 'N';
int key;
node *new_node, *root, *tmp, *parent;
node *get_node();
Anuradha Bhatia 22
6. Trees
root = NULL;
clrscr();
Anuradha Bhatia 23
6. Trees
case 2:
printf("\nEnter Element to be searched :");
scanf("%d", &key);
case 3:
if (root == NULL)
printf("Tree Is Not Created");
else {
printf("\nThe Inorder display : ");
inorder(root);
printf("\nThe Preorder display : ");
preorder(root);
printf("\nThe Postorder display : ");
postorder(root);
}
break;
}
} while (choice != 4);
}
/*
Get new Node
*/
node *get_node() {
Anuradha Bhatia 24
6. Trees
node *temp;
temp = (node *) malloc(sizeof(node));
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
/*
This function is for creating a binary search tree
*/
void insert(node *root, node *new_node) {
if (new_node->data < root->data) {
if (root->lchild == NULL)
root->lchild = new_node;
else
insert(root->lchild, new_node);
}
Anuradha Bhatia 25
6. Trees
*/
node *search(node *root, int key, node **parent) {
node *temp;
temp = root;
while (temp != NULL) {
if (temp->data == key) {
printf("\nThe %d Element is Present", temp->data);
return temp;
}
*parent = temp;
if (temp->data > key)
temp = temp->lchild;
else
temp = temp->rchild;
}
return NULL;
}
/*
This function displays the tree in inorder fashion
*/
void inorder(node *temp) {
if (temp != NULL) {
inorder(temp->lchild);
printf("%d", temp->data);
inorder(temp->rchild);
}
}
Anuradha Bhatia 26
6. Trees
/*
This function displays the tree in preorder fashion
*/
void preorder(node *temp) {
if (temp != NULL) {
printf("%d", temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}
/*
This function displays the tree in postorder
*/
void postorder(node *temp) {
if (temp != NULL) {
postorder(temp->lchild);
postorder(temp->rchild);
printf("%d", temp->data);
}
}
OPERATIONS ---
1 - Insert an element into tree
2 - Delete an element from the tree
3 - In order Traversal
4 - Preorder Traversal
5 - Post order Traversal
6 - Exit
Anuradha Bhatia 27
6. Trees
40
/ \
20 60
/\ \
10 30 80
\
90
Anuradha Bhatia 28
Graph and Hashing
CONTENTS
7.1 Introduction
1. Terminologies: graph, node (Vertices), arcs (edge),
directed graph, in-degree, out-degree, adjacent, successor,
predecessor, relation, weight, path, length.
7.2 Representations of a graph
1. Array Representation
2. Linked list Representation
7.3 Traversal of graphs
1. Depth-first search (DFS).
2. Breadth-first search (BFS).
7.4 Applications of Graph
7.5 Hashing
1. Hash function
2. Collision resolution techniques
Hours: 8
Marks: 16
Anuradha Bhatia 1
7. Graph and Hashing
Anuradha Bhatia 2
7. Graph and Hashing
Figure 7.1
Parallel edges or multiple edges are edges of the same type and
end-vertices
Self-loop is an edge with the end vertices the same vertex
Simple graphs have no parallel edges or self-loops
vii. The adjacency matrix for the above graph is as shown below
Anuradha Bhatia 3
7. Graph and Hashing
#include<stdio.h>
#include<conio.h>
int a[20][20],reach[20],n;
void dfs(int v)
{
int i;
reach[v]=1;
for(i=1;i<=n;i++)
if(a[v][i] && !reach[i])
{
printf("\n %d->%d",v,i);
dfs(i);
}
}
void main()
{
int i,j,count=0;
clrscr();
printf("\n Enter number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
reach[i]=0;
for(j=1;j<=n;j++)
Anuradha Bhatia 4
7. Graph and Hashing
a[i][j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1);
printf("\n");
for(i=1;i<=n;i++)
{
if(reach[i])
count++;
}
if(count==n)
printf("\n Graph is connected");
else
printf("\n Graph is not connected");
getch();
}
Anuradha Bhatia 5
7. Graph and Hashing
Anuradha Bhatia 6
7. Graph and Hashing
Anuradha Bhatia 7
7. Graph and Hashing
Anuradha Bhatia 8
7. Graph and Hashing
dfs( s, n );
break;
}
printf( "DO U WANT TO CONTINUE(Y/N) ? " );
scanf( "%c", &dummy );
scanf( "%c", &c );
}
while ( ( c == 'y' ) || ( c == 'Y' ) );
}
void bfs( int s, int n )
{
int p, i;
add
( s );
vis[ s ] = 1;
p = delete();
if ( p != 0 )
printf( " %d", p );
while ( p != 0 )
{
for ( i = 1;i <= n;i++ )
if ( ( a[ p ][ i ] != 0 ) && ( vis[ i ] == 0 ) )
{
add
( i );
vis[ i ] = 1;
}
p = delete();
if ( p != 0 )
printf( " %d ", p );
}
for ( i = 1;i <= n;i++ )
if ( vis[ i ] == 0 )
bfs( i, n );
}
void add( int item )
{
Anuradha Bhatia 9
7. Graph and Hashing
if ( rear == 19 )
printf( "QUEUE FULL" );
else
{
if ( rear == -1 )
{
q[ ++rear ] = item;
front++;
}
else
q[ ++rear ] = item;
}
}
int delete()
{
int k;
if ( ( front > rear ) || ( front == -1 ) )
return ( 0 );
else
{
k = q[ front++ ];
return ( k );
}
}
void dfs( int s, int n )
{
int i, k;
push( s );
vis[ s ] = 1;
k = pop();
if ( k != 0 )
printf( " %d ", k );
while ( k != 0 )
{
for ( i = 1;i <= n;i++ )
if ( ( a[ k ][ i ] != 0 ) && ( vis[ i ] == 0 ) )
{
push( i );
vis[ i ] = 1;
}
k = pop();
if ( k != 0 )
printf( " %d ", k );
}
Anuradha Bhatia 10
7. Graph and Hashing
7.5 Hashing
1. Hash function
(Question: Explain hashing with diagram – 4 Marks)
i. The problem at hands is to speed up searching.
ii. Consider the problem of searching an array for a given value.
iii. If the array is not sorted, the search might require examining each and
all elements of the array.
iv. If the array is sorted, we can use the binary search, and therefore
reduce the worse-case runtime complexity to O(log n).
v. We could search even faster if we know in advance the index at which
that value is located in the array.
Anuradha Bhatia 11
7. Graph and Hashing
Anuradha Bhatia 12
7. Graph and Hashing
Anuradha Bhatia 13
7. Graph and Hashing
-1
-1 -2
0 0 -1
0
0
-2
-1
0
-1
0
0
Anuradha Bhatia 14
7. Graph and Hashing
Anuradha Bhatia 15