Data Structures Basic Programs
Data Structures Basic Programs
COMPUTER ENGINEERING
PRACTICAL-1
1.1 Define various terms such as algorithm, various approaches to design an algorithm, time
complexity, space complexity, big ‘o’ notation, best case, average case and worst case time
complexity etc.
THEORY :
Algorithms
o A sequential solution of any program that written in human language,called algorithm.
o Algorithm is first step of the solution process, after the analysis of problem, programmer
write the algorithm of that problem
o Example of Algorithms:
Example : Write a algorithm to find out number is odd or even?
step 1 : start
step 2 : input number
step 3 : rem=number mod 2
step 4 : if rem=0 then
print "number even"
else
print "number odd"
endif
step 5 : stop
Flowchart
o Graphical representation of any program is called flowchart.
o There are some standard graphics that are used in flowchart as following:
1|Page
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Algorithm Efficiency
Some algorithms are more efficient than others. We would prefer to chose an efficient algorithm, so
it would be nice to have metrics for comparing algorithm efficiency.
The complexity of an algorithm is a function describing the efficiency of the algorithm in terms of
the amount of data the algorithm must process.
Usually there are natural units for the domain and range of this function. There are two main
complexity measures of the efficiency of an algorithm:
Time complexity is a function describing the amount of time an algorithm takes in terms of the
amount of input to the algorithm.
o "Time" can mean the number of memory accesses performed, the number of comparisons
between integers, the number of times some inner loop is executed, or some other natural
unit related to the amount of real time the algorithm will take.
o We try to keep this idea of time separate from "wall clock" time, since many factors
unrelated to the algorithm itself can affect the real time (like the language used, type of
computing hardware, proficiency of the programmer, optimization in the compiler, etc.).
o It turns out that, if we chose the units wisely, all of the other stuff doesn't matter and we can
get an independent measure of the efficiency of the algorithm.
Now we will discuss and understand the various notations used for Time
Complexity.
2|Page
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Big Omega denotes "more than or the same as" <expression> iterations.
Space complexity is a function describing the amount of memory (space) an algorithm takes in
terms of the amount of input to the algorithm.
o We often speak of "extra" memory needed, not counting the memory needed to store the
input itself.
o Again, we use natural (but fixed-length) units to measure this. We can use bytes, but it's
easier to use, say, number of integers used, number of fixed-sized structures, etc.
o In the end, the function we come up with will be independent of the actual number of bytes
needed to represent the unit.
o Space complexity is sometimes ignored because the space used is minimal and/or obvious,
but sometimes it becomes as important an issue as time.
o For example, we might say "this algorithm takes n2 time," where n is the number of items in
the input.
o Or we might say "this algorithm takes constant extra space," because the amount of extra
memory needed doesn't vary with the number of items processed.
3|Page
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
o For both time and space, we are interested in the asymptotic complexity of the algorithm:
When n (the number of items of input) goes to infinity, what happens to the performance of
the algorithm?
Big-O Notation
o Note :
o This is because, when N gets large enough, constants and low-order terms don't matter (a
constant-time method will be faster than a linear-time method, which will be faster than a
quadratic-time method).
o Formal definition: A function T(N) is O(F(N)) if for some constant c and for all values of
N greater than some value n0 : T(N) <= c * F(N)
The idea is that T(N) is the exact complexity of a method or algorithm as a function
of the problem size N, and that F(N) is an upper-bound on that complexity (i.e., the
actual time/space or whatever for a problem of size N will be no worse than F(N)).
In practice, we want the smallest F(N) -- the least upper bound on the actual
complexity.
4|Page
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
o Here is a list of classes of functions that are commonly encountered when analyzing the running
time of an algorithm. In each case, c is a constant and n increases without bound. The slower-
growing functions are generally listed first.
COMPUTER ENGINEERING
6|Page
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
#include <stdio.h>
// Linearly search x in arr[]. If x is present then return the index,
// otherwise return -1
int search(int arr[], int n, int x)
{
int i;
for (i=0; i<n; i++)
{
if (arr[i] == x)
return i;
}
return -1;
}
7|Page
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
8|Page
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
We must know the case that causes minimum number of operations to be executed.
In the linear search problem, the best case occurs when x is present at the first location.
So time complexity in the best case would be Most of the times, we do worst case analysis to
analyze algorithms.
In the worst analysis, we guarantee an upper bound on the running time of an algorithm which is
good information.
The average case analysis is not easy to do in most of the practical cases and it is rarely done. In
the average case analysis, we must know (or predict) the mathematical distribution of all possible
inputs.
The Best Case analysis is bogus. Guaranteeing a lower bound on an algorithm doesn’t provide any
information as in the worst case, an algorithm may take years to run.
For some algorithms, all the cases are asymptotically same, i.e., there are no worst and best cases.
For example, Merge Sort. Merge Sort does operations in all cases.
Most of the other sorting algorithms have worst and best cases.
For example, in the typical implementation of Quick Sort (where pivot is chosen as a corner
element), the worst occurs when the input array is already sorted and the best occur when the pivot
elements always divide array in two halves.
For insertion sort, the worst case occurs when the array is reverse sorted and the best case occurs
when the array is sorted in the same order as output.
9|Page
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
10 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
1.3 Implement array using row major order and column major order
PROGRAM :
#include <stdio.h>
#include <conio.h>
#define MAX 5
void main( )
{
int arr[5] ;
clrscr( ) ;
insert ( arr, 1, 11 ) ;
insert ( arr, 2, 12 ) ;
insert ( arr, 3, 13 ) ;
insert ( arr, 4, 14 ) ;
insert ( arr, 5, 15 ) ;
del ( arr, 5 ) ;
del ( arr, 2 ) ;
printf ( "\n\nAfter deletion: " ) ;
display ( arr ) ;
11 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
reverse ( arr ) ;
printf ( "\n\nAfter reversing: " ) ;
display ( arr ) ;
12 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
arr[i - 1] = arr[i] ;
arr[i - 1] = 0 ;
}
13 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
if ( i == MAX )
printf ( "\n\nThe element %d is not present in the array.", num ) ;
}
/* displays the contents of a array */
void display ( int *arr )
{
/* traverse the entire array */
int i ;
printf ( "\n" ) ;
for ( i = 0 ; i < MAX ; i++ )
printf ( "%d\t", arr[i] ) ;
}
OUTPUT :
Elements of Array
11
12
13
14
15
After deletion:
11
13
14
After insertion:
11
222
13
14
14 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
555
After reversing:
555
14
13
222
11
15 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
int search;
int flag;
int input( int *, int , int);
int list[200];
void linear_search(int * , int , int );
void display(int *, int);
/* Definition of function */
void linear_search(int l[], int n, int element)
{
int k;
flag = 1;
for(k = 0; k< n; k++)
{
if(l[k] == element)
{
printf("\n Search is successful \n");
printf("\n Element: %i Found at Location: %i", element, k+1);
flag = 0 ;
}
}
if (flag)
printf("\n Search is unsuccessful");
}
16 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
17 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
key = search ;
printf("\n Entered list as follows:\n");
display(list,number);
linear_search(list, number, key);
printf("\n In the following list\n");
display(list,number);
getch();
}
OUTPUT :
Input the number of elements in the list: 6
a[0]=3
a[1]=4
a[2]=6
a[3]=1
a[4]=8
a[5]=9
Enter key value to be search: 8
Search is successful
Element: 8 Found at Location: 5
18 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
COMPUTER ENGINEERING
beg=a[0];
end=a[9];
mid=(beg+end)/2;
printf(“\nenter the number to be searched: “);
scanf(“%d”,&target);
while(beg<=end && a[mid]!=target)
{
if(target<a[mid])
end=mid-1;
else
beg=mid+1;
mid=(beg+end)/2;
}
if(a[mid]==target)
{
printf(“\nthe number is found at position %2d”,mid);
}
else
{
printf(“\nthe number is not found: “);
}
getch();
}
Output:
enter the total numbers:5
enter the array elements: a[0]=3
a[1]=4
a[2]=6
a[3]=1
20 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
a[4]=8
the sorted numbers are: a[0]=1
a[1]=3
a[2]=4
a[3]=6
a[4]=8
enter the number to be searched:6
the number is found at position: 2
21 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
PRACTICAL-2
2.1 Implement various string algorithms
Algorithm for string length.
Step1 : [ Iinitialigation]
Len 0
Step2 : [Read string & increament counter]
while (str<>null)repeat
Lenlen+1
Step3 : while(“length of string len”)
Step4 : [finished]
Exit.
PROGRAM:
#incude<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
int len=0;
char str[10];
clrscr();
printf(“Enter String:”);
scanf(“%s”&str);
while(str[len]!=’\0’)
{
len++;
}
printf(“Length of String:”,len);
getch();
}
22 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
OUTPUT:
Enter String : Mansi
Length of String : 5
Algorithm for copy string:
Step1: [initilization]
Str1 null
i0
j0
Step2 : [copy operation performed]
While (j<>strlen(str2))repeat
(a)str2[i] str[i]
(b)i =i+1_
(c)j =j+1
Step3 : [print the string after the copy operation performed]
Write(“str1”)
Step4 : [Finished]
Exit.
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
Char str1[10] = ” ”;
Char str2[10] = ” Mansi ”;
int i,j,len=0;
i=0,j=0;
len=strlen(str2);
clrscr();
23 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
while(j!=strlen(str2))
{
Str1[j]=str2[i];
i++;
j++;
}
Printf(“Your copy string is:”,str1)
getch();
}
OUTPUT:-
Your copy string is : Mansi
Algorithm for concatenation operation
Step1 : [Initializatoin]
Str3null
i 0 // i for str1
j 0 // j for str2
k 0 // k for str3
Step2 : [copy str1 string in to str3 ]
While(j<>len(str1))repeat
(a)str3[k] str1[j]
(b)i i+1
(c)kk+1
Step3 : [append str2 string in to str3]
While(j<>len(str2))repeat
(a)str3[k] str2[j]
(b)j j+1
(c)kk+1
Step4 : [print the string after concatenation operation performed]
Write(“str3”)
24 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Step5 : [Finished]
Exit.
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
int i,j,k;
char str[10]=” khusbu ”;
char str[10]=” panchal ”;
char str[30]=” ”;
i=0,j=0,k=0,len=0;
clrscr();
while(i!=strlen(str1))
{
str3[k]=str1[i];
i++;
k++;
}
while(i!=strlen(str2))
{
str3[k]=str2[j];
j++;
k++;
}
printf(“Your string is:”,str3);
getch();
}
25 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
OUTPUT:-
Your string is: Mansi Shah
Algorithm for string comparision:-
Step1 : [Initilization]
i 0
j0
flag 0
temp 0
Step2 : [read two string]
read[str1]
read[str2]
Step3 : [find length of both string]
l1=strlen(str1)
l2=strlen(str2)
Step4 : [check length of both string]
if(l1<>l2)
then
write(“not equal”)
Step5 : [compare char by char]
repeat while(i<=l1)
if(str1[i]==str2(i))
then
flag=1
write(“equal”)
exit
Step6 : if(flag==0)
then
write(“not equal”)
Step7 : [finished]
26 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Exit.
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str1[10],str2[10];
int i=0,l1=0,l2=0,flag=0;
clrscr();
printf(“Enter first string:”);
scanf(“%s”,&str1);
printf(“Enter second string:”);
scanf(“%s”&,str2);
l1=strlen(str1);
l2=strlen(str2);
printf(“/n Your string is:”,l1);
printf(“/n Your string is:”,l2);
if(l1!=l2)
{
Flag=0;
}
else
{
for(i=0;i<l1;i++)
{
if(str1[i]=str2[i])
{
flag=1;
27 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
}
}
}
if(flag==1)
{
printf(“same string”);
}
else
{
printf(“not same string”);
}
getch();
}
OUTPUT:-
Enter first string: Manshi
Enter second string: Manshi
Your string is: 6
Your string is: 6
Same string
Algorithm for substring operation:-
Step1 : [Intilization]
i0
str2 null
Step2 : [Input the value]
Read[str,cursor,num]
Step3 : while(num<>0)repeat
str[i] str[cursor]
cursor cursor+1
28 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
i i+1
num num-1
Step4 : [print original string and substring]
write(“subject”)
write(“str”)
Step5 : [finished]
Exit.
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main
{
int i=0,sp,num;
char str1[10],str2[10];
int len=0;
printf(“Enter your string:”);
scanf(“%s”,&str);
printf(“Enter your string position:”);
scanf(“%d”,&sp);
printf(“Enter the no of char:”);
scanf(“%d”,&num);
while(nmu!=0)
{
Str2[i]=str[sp];
S++;
i++;
num--;
}
29 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
30 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
PRACTICAL-3
3.1 Implement push and pop algorithms of stack using array
Algorithm
PUSH ( S,TOP,X)
S : S is a vector which is capable to store maximum of n elements.
TOP : Index of the top most element in a stack.
Step 1: If TOP >=N
then Write (‘ STACK OVERFLOW’)
Return.
Step 2 : TOP ← TOP+1.
Step 3 : S[TOP] ←X
Step 4 : EXIT
POP ( S,TOP)
S : S is a vector which is capable to store maximum of n elements.
TOP : Index of the top most element in a stack.
Step 1 : If TOP = 0
then Write (‘ STACK UNDERFLOW’)
Return.
Step 2 : Return (S[TOP+1])
Step 3 : TOP ← TOP-1.
PROGRAM:
#define MAXSIZE 10
struct st
{
int top;
int stack[MAXSIZE];
};
struct st s;
31 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
int empty(void);
int full(void);
void push(void);
void pop(void);
void display(void);
void main()
{
char ans;
int ch;
do
{
clrscr();
printf("********Stack Program**********\n");
printf("1.PUSH\n");
printf("2.POP\n");
printf("3.DISPLAY\n");
printf("4.QUIT\n");
printf("Enter Your Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
32 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
display();
break;
case 4:
exit(1);
break;
default:
printf("INVALID CHOICE!!!!!!!!!!!!!!!!\n");
break;
}
printf("Want To Go To The Main Menu[y/n]");
flushall();
ans = getch();
}
while(ans == 'y' ans == 'Y');
printf("\nPress Any Key To Exit");
getch();
}
int full(void)
{
if (s.top == MAXSIZE)
return(1);
else
return(0);
}
int empty(void)
{
if (s.top == 0)
return(1);
33 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
else
return(0);
}
void push(void)
{
char ch;
int x;
do
{
if(full() == 1)
{
printf("\nStack Full\n");
break;
}
else
{
s.top = s.top + 1;
printf("\nEnter An Element To Be Pushed: ");
scanf("%d",&x);
s.stack[s.top] = x;
}
printf("\nDo You Want To Push More Elements[y/n]");
flushall();
ch = getch();
}while(ch == 'y' ch == 'Y');
}
void pop(void)
{
char ch;
34 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
do
{
if(empty() == 1)
{
printf("\nStack Empty\n");
break;
}
else
{
printf("\n%d has been popped !",s.stack[s.top]);
s.top = s.top - 1;
}
printf("\nDo you Want To Pop Out More?[y/n]");
flushall();
ch = getch();
}while(ch == 'Y' ch == 'y');
}
void display(void)
{
int i;
clrscr();
if(empty() == 1)
printf("\nStack Empty!!!");
else
{
printf("Displaying Stack............\n");
for(i = s.top; i>0;i--)
printf("%d",s.stack[i]);
35 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
}
}
OUTPUT :
1.push
2.pop
3.display
4.exit
enter your choice : 1
enter a value to push : 11
1.push
2.pop
3.display
4.exit
enter your choice : 1
enter a value to push : 22
1.push
2.pop
3.display
4.exit
enter your choice : 3
op->22 11
1.push
2.pop
3.display
4.exit
enter your choice : 2
poped 22
1.push
2.pop
36 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
3.display
4.exit
enter your choice : 3
op->11
37 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
38 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
39 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
else
{
/* go to next node */
l = 1 + length ( q -> link ) ;
return ( l ) ;
}
}
OUTPUT :
Length of Linked List = 5
40 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
void insert(int);
int delet(int);
void display(void);
int queue[3];
int rear=-1;
41 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
int front=-1;
void main()
{
int n=3;
char op;
clrscr();
do
{
printf("\nOptions");
printf("\nPress i for insertion");
printf("\nPress d for deletion");
printf("\nPress p for display");
printf("\nPress e for exit");
op=getche();
switch(op)
{
case 'i' : insert(n);break;
case 'd' : delet(n);break;
case 'p' : display(); break;
default : printf("\nWrong operator");
}
}while(op!='e');
getch();
}
void insert(int n)
{
int item;
42 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
if((front==0&&rear==n)||(front==rear+1))
{
printf("\nQueue over flow");
return;
}
if(front==-1)
{
front=0;
rear=0;
}
else if(rear==n)
rear=0;
else
rear=rear+1;
printf("\nEnter the item to be inserted");
scanf("%d",&item);
queue[rear]=item;
}
int delet(int n)
{
int item;
if(front==-1)
{
printf("\nQueue is empty");
return;
}
printf("\nYou have deleted %d",queue[front]);
queue[front]=0;
43 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
if(front==rear)
{
front=-1;
rear=-1;
}
else if(front==n)
front=0;
else
front=front+1;
return;
}
void display(void)
{
int i;
printf("\nDisplaying Queue\n");
for(i=0;i<3;i++)
printf("\n%d",queue[i]);
}
OUTPUT :
Options :
Press i for insertion
Press d for deletion
Press p for display
Press e for exit
enter your choice : i
Enter the item to be inserted : 11
44 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Options :
Press i for insertion
Press d for deletion
Press p for display
Press e for exit
enter your choice : i
Enter the item to be inserted : 22
Options:
Press i for insertion
Press d for deletion
Press p for display
Press e for exit
enter your choice : p
Displaying Queue : 11
22
Options :
Press i for insertion
Press d for deletion
Press p for display
Press e for exit
enter your choice : d
you have deleted : 11
Options:
Press i for insertion
Press d for deletion
45 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
46 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
47 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
48 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
while(1)
{
printf("Select Your Choice:\n");
printf("(1) PUSH\n");
printf("(2) POP\n");
printf("(3) Display\n");
printf("Enter Your Choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter Element:");
scanf("%d",&x);
push(CQUEUE,x);
break;
case 2:
pop(CQUEUE);
break;
case 3:
display(CQUEUE);
break;
case 4:
exit(0);
}
}
}
void push(int *CQUEUE,int x)
{
if(REAR>=SIZE-1 && FRONT==0)
49 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
50 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
{
if(FRONT==SIZE-1)
FRONT=0;
else
FRONT=FRONT+1;
}
}
}
void display(int *CQUEUE)
{
int i;
if(FRONT==-1)
printf("Circular Queue is Empty\n");
else if(REAR>=FRONT)
{
for(i=FRONT;i<=REAR;i++)
printf("%d\n",CQUEUE[i]);
}
else
{
for(i=FRONT;i<=SIZE-1;i++)
printf("%d\n",CQUEUE[i]);
for(i=0;i<=REAR;i++)
printf("%d\n",CQUEUE[i]);
}
}
OUTPUT :
COMPUTER ENGINEERING
(1) PUSH
(2) POP
(3) Display
22 5 11 14 17
52 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
PRACTICAL-4
4.1 Implement simple structure programs using pointers
#include <stdio.h>
#include<stdlib.h>
struct name {
int a;
float b;
char c[30];
};
int main(){
struct name *ptr;
int i,n;
printf("Enter n: ");
scanf("%d",&n);
ptr=(struct name*)malloc(n*sizeof(struct name));
/* Above statement allocates the memory for n structures with pointer ptr pointing to base address */
for(i=0;i<n;++i){
printf("Enter string, integer and floating number respectively:\n");
scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);
}
printf("Displaying Infromation:\n");
for(i=0;i<n;++i)
printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);
return 0;
}
Output:
Enter n: 2
Enter string, integer and floating number respectively:
53 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Programming
2
3.2
Enter string, integer and floating number respectively:
Structure
6
2.3
Displaying Information
Programming 2 3.20
Structure 6 2.30
54 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
4.2 Implement insertion of node in the beginning of the list, at any position and at the
end of list, Implement insertion of node in the beginning of the list, at any position
and at the end of list in singly linked list
ALGORITHM:
Insertion at beginning[x,first]
Step 1 [check for availability list under flow]
If(avail=null)
Then
Write(“availability list underflow “)
Return(first)
Step 2 [check whether any node exist or not]
(a)[if there is no any node in the list then remove free node from availability list]
(1)if (first=null)
Temp<- avail
Avail<-link[avail]
Step 3 [assign data to node]
Info[temp]<-x
Step 4 [if there is no node and location is (1)]
(1)[assign address of first node to temp]
Link[temp]<-null
(2)[assign address of temp pointer to first pointer]
First<-temp
Step 5 [if the node exist and to insert a new node at a specific location N]
(1)[assign address of first node to temp]
Tmp<-first
(2)[traverse the list until last node or upto the given specific location]
Repeat while(link(tmp)!=N)
tmp<-link[tmp]
free(tmp)
55 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Step 6 [finished]
Exit
PROGRAM :
#include<conio.h>
#include<stdio.h>
struct node
{
int i;
struct node *next;
};
void main()
{
struct node *first;
struct node *last;
struct node *temp;
int ch,user,add,cnt=0,t=0;
struct node *p;
clrscr();
printf("\n\t 1.CREATION");
printf("\n\t 2.INSERT AT STARTING");
printf("\n\t 3.INSERT AT MIDDLE(USER'S CHOICE)");
printf("\n\t 4.INSERT AT END");
printf("\n\t 5.DELETE 1ST NODE");
printf("\n\t 6.DELETE LAST NODE");
printf("\n\t 7.DELETE MIDDLE NODE(USER'S CHOICE)");
printf("\n\t 8.DISPLAY");
printf("\n\t 10.EXIT");
scanf("%d",&user);
56 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
while(user!=10)
{
if(user==1)
{
printf("\n\t ENTER DATA ::: ");
first=(struct node*)malloc(sizeof(struct node));
scanf("%d",&ch);
first->i=ch;
first->next=0;
p=first;
cnt=1;
}
if(user==2)
{
p=(struct node*)malloc(sizeof(struct node));
printf("\n\t ENTER DATA FOR 1ST NODE");
scanf("%d",&p->i);
p->next=first;
first=p;
cnt++;
}
if(user==3)
{
printf("\n\t ENTER ANY ADDRESS BETWEEN 1 and %d",cnt);
scanf("%d",&add);
t=1;
p=first;
while(t!=add)
{
57 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
p=p->next;
t++;
}
temp=(struct node*)malloc(sizeof(struct node));
printf("\n\t ENTER DATA FOR NODE");
scanf("%d",&temp->i);
temp->next=p->next;
p->next=temp;
cnt++;
}
if(user==4)
{
p=(struct node*)malloc(sizeof(struct node));
printf("\n\t ENTER DATA FOR LAST NODE");
scanf("%d",&p->i);
temp=first;
while(temp->next!=0)
{
temp=temp->next;
}
temp->next=p;
p->next=0;
cnt++;
}
if(user==5)
{
p=first;
first=p->next;
free(p);
58 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
}
if(user==6)
{
p=first;
while(p->next->next!=0)
{
p=p->next;
}
p->next=0;
free(p->next->next);
}
if(user==7)
{
printf("\n\t ENTER ANY ADDRESS BETWEEN 1 and %d",cnt);
scanf("%d",&add);
t=1;
p=first;
while(t<add-1)
{
p=p->next;
t++;
}
temp=p->next;
p->next=temp->next;
free(temp);
cnt--;
}
if(user==8)
59 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
{
p=first;
while(p!=0)
{
printf("\n\t %d",p->i);
p=p->next;
}
}
printf("\n\t 1.CREATION");
printf("\n\t 2.INSERT AT STARTING");
printf("\n\t 3.INSERT AT MIDDLE(USER'S CHOICE)");
printf("\n\t 4.INSERT AT END");
printf("\n\t 5.DELETE 1ST NODE");
printf("\n\t 6.DELETE LAST NODE");
printf("\n\t 7.DELETE MIDDLE NODE(USER'S CHOICE)");
printf("\n\t 8.DISPLAY");
printf("\n\t 10.EXIT");
scanf("%d",&user);
}
getch();
}
OUTPUT:
1.CREATION
2.INSERT AT STARTING
3 INSERT AT MIDDLE(USER'S CHOICE)
4.INSERT AT END
5.DELETE 1ST NODE
6.DELETE LAST NODE
60 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
61 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
head = inert(head,n);
printf(“\n”);
62 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
if(list->number == -999)
{
list->next = NULL;
}
else/* create next node */
{
list->next = (node *)malloc(sizeof(node));
create(list->next);
}
return:
}
void print(node *list)
{
if(list->next != NULL)
{
printf(“%d -->”, list->number);
if(list ->next->next = = NULL)
printf(“%d”, list->next->number);
print(list->next);
}
63 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
return:
}
node *insert(node *head, int x)
{
node *p1, *p2, *p;
p1 = NULL;
p2 = head; /* p2 points to first node */
for( ; p2->number < x; p2 = p2->next)
{
p1 = p2;
if(p2->next->next == NULL)
{
p2 = p2->next; /* insertion at end */
break;
}
}
/*key node found and insert new node */
p = (node )malloc(sizeof(node)); / space fornew node */
p->number = x; /* place value in the new node */
p->next = p2; /*link new node to key node */
if (p1 == NULL)
head = p; /* new node becomes the first node */
else
p1->next = p; /* new node inserted in middle */
return (head);
}
OUTPUT :
Input a number
(type –999 at end ) : 10
64 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Input a number
(type –999 at end ) : 20
Input a number
(type –999 at end ) : 30
Input a number
(type –999 at end ) : 40
Input a number
(type –999 at end ) : 999
Original list: 10 -->20-->30-->40-->-999
65 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
4.4 Implement searching of a node and counting no of node algorithms in singly linked
list.
ALGORITHM FOR SEARCH A NODE:
- Let x be the element to search
void SEARCH(x)
Begin
found =0
current =head
while (current !=null)
{
if(current ->info=x
{
found=1
break
}
current=current->next
}
if(found=1)
print ”Element found”
else
print “Not found"
End.
----------------------------------
PROGRAM :
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
66 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
67 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
{
*head = temp;
(*head)->next = NULL;
}
else
{
temp->next = *head;
*head = temp;
}
}
}
void search(struct node *head, int key, int index)
{
if (head->a == key)
{
printf("Key found at Position: %d\n", index);
}
if (head->next == NULL)
{
return;
}
search(head->next, key, index - 1);
}
void delete(struct node **head)
{
struct node *temp;
while (*head != NULL)
{
temp = *head;
68 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
*head = (*head)->next;
free(temp);
}
}
OUTPUT :
Enter the number of nodes: 6
1 4 3 1 5 1
Enter key to search: 1
Key found at Position: 6
Key found at Position: 4
Key found at Position: 1
ALGORITHM FOR COUNTING NO OF NODE IN SINGLY LINKED LIST :
STEP 1 : Start
STEP 2 : check if the list is empty or not
if phead ==NULL
OUTPUT ‘Zero nodes’ and exit
else goto step 3
STEP 3 : Set the head pointer to a temporary variable
last=phead
STEP 4 : Traverse till the last node
SET while(last->next!= NULL)
{
increase the node count by 1
SET count++
point to the next node in the list
SET last=last->next
}
STEP 5 : Increase the value of count by 1 for last node if the list has more than one node otherwise this
condition is applicable if the list has exactly one node.
69 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
70 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
}
var->next=NULL;
temp->next=var;
}
}
int count_node()
{
int i=0;
temp=head;
while(temp!=NULL)
{
i++;
temp=temp->next;
}
printf("\n\nnumber of nodes are %d ",i);
}
void display()
{
struct node *var;
var=head;
printf("\nlist of elments are \n");
while(var!=NULL)
{
printf("-> %d ",var->data);
var=var->next;
}
}
int main()
{
71 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
int i,value;
char ch='y';
head=NULL;
72 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
count_node();
break;
}
case 4 :
{
exit(0);
break;
}
}
}
getch();
}
OUTPUT :
1.) Insert node
2.) Display the list
3.) Count number of nodes
4.) Exit
Choose to do operation : 1
Enter the data to be inserted in node 20
Choose to do operation : 1
Enter the data to be inserted in node 30
Choose to do operation : 1
Enter the data to be inserted in node 40
Choose to do operation : 2
List of elements are:
20 --> 30 --> 40
73 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Choose to do operation : 3
Number of nodes are 3
Choose to do operation : 4
74 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
4.5 Implement insertion of node in the beginning of the list, at any position and at the
end of list, Implement insertion of node in the beginning of the list, at any position
and at the end of list in doubly linked list.
ALGORITHM FOR INSERT A NODE AT BEGINNING:
Alorithm:- Doubly_insert(first,x,next,prev)
STEP 1: [Check for any node exist or not]
STEP 2: [finished]
75 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Return
76 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Alorithm:- Doubly_insloc(first,x,next,prev)
77 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
avail<-link[avail]
78 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
clrscr();
printf("\n\t 1. CREATE.");
printf("\n\t 2. INSERT.");
printf("\n\t 3. DELETE.");
printf("\n\t 4. DISPLAY.");
printf("\n\t 5.EXIT.");
scanf("%d",&ch);
while(ch!=5)
{
if(ch==1)
{
cnt=0;
head=(struct doubly *)malloc(sizeof(struct doubly));
head->back=0;
head->front=0;
printf("\n\t ENTER DATA SUCEESFULLY::: ");
scanf("%d",&head->i);
cnt++;
last=head;
}
if(ch==2)
{
printf("\n\t 1. INSERTION AT FRONT.");
printf("\n\t 2. INSERTION AT MIDDLE.");
printf("\n\t 3. INSERTION AT END.");
scanf("%d",&intch);
temp=(struct doubly *)malloc(sizeof(struct doubly));
printf("\n\t ENTER DATA:::");
79 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
scanf("%d",&temp->i);
if(intch==1)
{
temp->front=0;
temp->back=head;
head=temp;
cnt++;
}
if(intch==2)
{
printf("\n\tNTER VALUE BETVN 1--%d",cnt);
scanf("%d",&add);
t=1;
p=head;
while(t<add)
{
p=p->back;
t++;
}
temp->back=p->back;
p->back->front=temp;
p->back=temp;
temp->front=p;
}
if(intch==3)
{
p=head;
while(p->back!=0)
{
80 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
p=p->back;
}
temp->back=0;
temp->front=p;
p->back=temp;
cnt++;
}
}
if(ch==3)
{
printf("\n\t1. DELETE FRONT");
printf("\n\t2. DELETE MIDDLE");
printf("\n\t3. DELETE END");
scanf("%d",&intch);
if(intch==1)
{
head->back=t;
free(head);
head=t;
head->front=0;
cnt--;
}
if(intch==2)
{
printf("\n\tNTER VALUE BETVN 1--%d",cnt);
scanf("%d",&add);
t=1;
p=head;
while(t<(add-1))
81 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
{
p=p->back;
t++;
}
temp=p->back;
p->back=temp->back;
temp->back->front=p;
free(temp);
}
if(intch==3)
{
p=head;
while(p->back!=0)
{
p=p->back;
}
temp->front=p;
p->back=temp;
temp->back=0;
cnt--;
}
}
if(ch==4)
{
p=head;
while(p!=0)
{
printf("\t-->%d",p->i);
p=p->back;
82 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
}
printf("\n\t total nodes %d",cnt);
}
if(ch==5)
exit(0);
printf("\n\t 2. INSERT.");
printf("\n\t 3. DELETE.");
printf("\n\t 4. DISPLAY.");
printf("\n\t 5.EXIT.");
scanf("%d",&ch);
}
getch();
}
OUTPUT :
1. CREATE
2. INSERT
3. DELETE
4. DISPLAY
5. EXIT
ENTER YOUR CHOICE : 1
ENTER DATA SUCEESFULLY ….
1. CREATE
2. INSERT
3. DELETE
4. DISPLAY
5. EXIT
ENTER YOUR CHOICE : 5
83 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
struct node
{
int data;
struct node *next,*first=NULL;
}*head,*temp;
void main()
84 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
{
int i=0,x;
printf(“enter data to search”);
scanf(“%d”,&x);
head=first;
temp=head;
while(temp!=NULL )
{
if(temp[data]=x)
printf(“data found ”);
else()
printf(“no data available”);
temp=temp->next;
}
getch();
}
OUTPUT :
12, 34, 23
Enter data to search
ALGORITHM FOR COUNTING NO OF NODE IN DOUBLY LINKED LIST :
Counting (first)
Step1 [initialization]
Count=0
Temp=first
Step2 if (temp==NULL) then
Write (“no nodes exist”)
Exit
Step3 [traverse till end and increase count at each traverse]
85 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Repeat while(next[temp]!=NULL)
Count=count+1
Step4 write (“ count nodes exist”)
Step5 [finished]
Exit
PROGRAM :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next,*first=NULL;
}*head,*temp;
void main()
{
int i=0;
head=first;
temp=head;
while(temp!=NULL )
{
i++;
temp=temp->next
}
printf(“total number of nodes= %d”,&i)
getch();
}
86 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
OUTPUT :
total number of nodes= 3
87 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
PRACTICAL-5
5.1 Implement Bubble sort, Selection sort algorithms
ALGORITHM FOR BUBBLE SORT :
The list is divided into two sublists: sorted and unsorted.
The smallest element is bubbled from the unsorted list and moved to the sorted sublist.
After that, the wall moves one element ahead, increasing the number of sorted elements and
decreasing the number of unsorted ones.
Each time an element moves from the unsorted part to the sorted part one sort pass is
completed.
Given a list of n elements, bubble sort requires up to n-1 passes to sort the data.
template <class Item>
void bubleSort(Item a[], int n)
{
bool sorted = false;
int last = n-1;
for (int i = 0; (i < last) && !sorted; i++)
{
sorted = true;
for (int j=last; j > i; j--)
{
if (a[j-1] > a[j]
{
swap(a[j],a[j-1]);
sorted = false; // signal exchange
}
}
}
PROGRAM :
88 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,t;
clrscr();
printf("\n\n Enter Values:\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for(i=9;i>0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
printf("\n\n Sorted Array Is:");
for(i=0;i<10;i++)
{
printf("\n%d",a[i]);
}
getch();
89 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
}
OUTPUT :
Enter Values:
65
12
02
65
98
31
5
40
78
21
Sorted Array Is:
2
5
12
21
31
40
65
65
78
98
ALGORITHM FOR SELECTION SORT :
template <class Item>
void selectionSort( Item a[], int n) {
for (int i = 0; i < n-1; i++) {
int min = i;
90 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
91 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\n\nSorted Values:");
for(i=0;i<10;i++)
{
printf("\n%d",a[i]);
}
getch();
}
OUTPUT :
Selection Sort
Enter Values:6
9
4
3
2
1
5
25
60
56
Sorted Values:
92 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
1
2
3
4
5
6
9
25
56
60
93 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
94 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
}
else
{
rtarr[rtidx]=A[k];
rtidx++;
}
}
k=a;
for(l=0;l<ltidx;++l)A[k++]=leftarr[l];
A[k++]=pivot;
for(l=0;l<rtidx;++l)A[k++]=rtarr[l];
if(ltidx>0)quicksort(a,a+ltidx-1);
if(rtidx>0)quicksort(b-rtidx+1,b);
}
void printarr(int a)
{
int i;
for(i=0;i<a;i++)
{
printf("%d",A[i]);
printf("\n");
}
}
main()
{
int i,s;
clrscr();
printf("enter the number of numbers to be entered \n");
scanf("%d",&s);
95 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
for(i=0;i<s;i++)
{
printf("enter the number \n" );
scanf("%d",&A[i]);
}
printf("\n array before sorting\n ");
printarr(s);
quicksort(0,s-1);
printf("\n array after sorting:\n");
printarr(s);
getch();
}
OUTPUT :
enter the number of numbers to be entered
60
enter the number
57
enter the number
30
enter the number
51
enter the number
6
enter the number
32
enter the number
35
array before sorting
60
96 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
57
30
51
6
32
35
array after sorting:
6
30
32
35
51
57
60
97 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
for(i=1;i<num;i++){
temp=a[i];
j=i-1;
98 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
while((temp<a[j])&&(j>=0)){
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
return 0;
}
OUTPUT :
Enter total elements: 5
Enter 5 elements: 9 4 1 0 2
After sorting: 0 1 2 4 9
ALGORITHM FOR SHELL SORT :
# Sort an array a[0...n-1].
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
99 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
}
PROGRAM :
#include<stdio.h>
#include<conio.h>
void shell_sort(int [],int);
void main()
{
int a[50],n,val,pos,i;
clrscr();
printf("How many elements are there?");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d",&a[i]);
}
shell_sort(a,n);
100 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
getch();
}
void shell_sort(int a[],int n)
{
int gap,i,temp,exch;
for(gap=n/2;gap>=1;gap=gap/2)
{
do
{
exch=0;
for(i=0;i<n-gap;i++)
{
if(a[i]>a[i+gap])
{
temp=a[i];
a[i]=a[i+gap];
a[i+gap]=temp;
exch=1;
}
}
printf("\n gap=%d:",gap);
for(i=0;i<n;i++)
{
printf("%d",a[i]);
}
}while(exch==1);
}
}
OUTPUT :
101 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
gap=2:11 5 7 21 23
gap=1:5 7 11 21 23
102 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
103 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
/* Definition of function */
bubble_sort(int n, int l[])
{
int flag = 1 ;
int i, j, k, temp;
for(j = 0 ; j< n - 1; j++)
{
for(k = 0 ; k< n - j - 1 ; k++)
{
if(l[k] > l[k+1])
{
temp = l[k];
l[k] = l[k+1];
104 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
l[k+1] = temp ;
flag = 0;
}
}
if(flag)
break ;
else
flag = 1;
}
printf("\n Entered list as follows in");
printf("\n Ascending order: ");
for(i = 0 ; i < n ; i++)
printf(" %d", l[i]);
return 0 ;
}
/* Definition of function */
merge_sort( int n, int list_a[], int m ,
int list_b[], int result_list[] )
{
int i = 0;
int j = 0;
int k = 0;
int ch, l;
/* Repeat the process until the elements of list_a and list_b are exhausted */
while((i < n) &&(j<m))
{
if(list_a[i] < list_b[j])
{
result_list[k] = list_a[i];
105 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
i++;
k++;
} /* end of if statement */
Else if(list_a[i] > list_b[j])
{
result_list[k] = list_b[j];
j++;
k++;
} /* end of if statement */
else
{
result_list[k] = list_a[i];
i++;
j++;
k++;
} /* end of else statement */
printf("\n");
for(ch = 0; ch < k; ch++)
printf(" %d", result_list[ch]);
} /* end of while statement */
/* checks if size of list_a larger than list_b copy rest of the elements of list_a into result_list */
if(i <n )
{
for(l = i ; l <n ; l++)
{
result_list[k] = list_a[i];
i++;
k++;
printf("\n");
106 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
107 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
108 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Enter Values:
65
12
02
65
31
5
40
78
21
Sorted Array Is:
2
5
12
21
31
40
65
65
78
109 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
5.5 Solve hash table example using division method, method square method, folding
method (paper work only)
THEORY :
Hash table : Element's index in the table is a function of its value
Advantage : fast lookup, fast indexing
O(1)!
Trick : getting unique values from the keys, or storing keys in unique locations, or both Typically, table =
array
Definitions
Hash function : maps a key, k, to an index (address) in the table Perfect hash function: function that maps
each key to a unique index.
Collision : occurs when more than one key maps to the same index More on hash functions
If we have n items in a table with m positions, we have mn possible hash functions
Q: How many of these are perfect hash functions?
m items taken n at a time: mPn = m!/(m-n)!
perfect hash functions are pretty rare Several types:
division functions
folding functions
mid-square functions
extraction functions
radix functions
Hashing by division
Actually modulo division
Use size of table as modulus to ensure unique indices (or a prime number
greater than the table's size)
Most other methods utilize modulo division too
Advantages:
o Simple
110 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
Hashing by folding
Idea : divide the key into parts, then combine (.fold.) the parts to create the index
Shift folding : parts are placed underneath one another, then added
Boundary folding : same as shift folding, except that every other part is written backwards Usually
followed by modulo division
Example : Key is 23459087632
Divide into parts: 234 590 876 32
Shift folding: 234 + 590 + 876 + 32 = 1732
Boundary folding: 234 + 095 + 876 + 23 = 1228
Hashing by computing the mid-square
Idea : square the key, use the .middle. as the address
Example : 96012 -> 9218304144 -> 8304 is hash
Advantage : entire key is used to calculate the address, reducing chances of collisions Can do bit-wise w/ a
mask and shifting
Applications of hash tables
Lots of recent research into using distributed hash tables in peer-to-peer networks (searching,
lookup)
Symbol tables (compilers)
Databases (of phone numbers, IP addresses, etc.)
Dictionaries
111 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
PRACTICAL-6
6.1 Implement construction of binary search tree
ALGORITHM :
Here k is the key that is searched for and x is
the start node.
BST-Search(x, k)
1: y ← x
2: while y 6= nil do
3: if key[y] = k then return y
4: else if key[y] < k then y ← right[y]
5: else y ← left[y]
6: return (“NOT FOUND”)
PROGRAM :
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct node
{
struct node *left ;
char data ;
struct node *right ;
};
112 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
char arr[ ] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', '\0', '\0', 'H' } ;
int lc[ ] = { 1, 3, 5, -1, 9, -1, -1, -1, -1, -1 } ;
int rc[ ] = { 2, 4, 6, -1, -1, -1, -1, -1, -1, -1 } ;
void main( )
{
struct node *root ;
clrscr( ) ;
root = buildtree ( 0 ) ;
printf ( “In-order Traversal:\n” ) ;
inorder ( root ) ;
getch( ) ;
}
113 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
}
void inorder ( struct node *root )
{
if ( root != NULL )
{
inorder ( root -> left ) ;
printf ( "%c\t", root -> data ) ;
inorder ( root -> right ) ;
}
}
OUTPUT :
In-Order Traversal :
D B H E A F C G
114 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
6.2 Implement inorder, preorder and postorder traversal methods in binary search
tree
ALGORITHM :
1: if x = nil then return (“Empty Tree”)
2: y ← x
3: while left[y] 6= nil do y ← left[y]
4: return (key[y])
PROGRAM :
#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
}
*root = NULL, *temp = NULL, *t2, *t1;
void delete1();
void insert();
void delete();
void inorder(struct btnode *t);
void create();
void search(struct btnode *t);
115 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
int flag = 1;
void main()
{
int ch;
printf("\nOPERATIONS ---");
printf("\n1 - Insert an element into tree\n");
printf("2 - Delete an element from the tree\n");
printf("3 - Inorder Traversal\n");
printf("4 - Preorder Traversal\n");
printf("5 - Postorder Traversal\n");
printf("6 - Exit\n");
while(1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
insert();
break;
case 2:
delete();
break;
116 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
case 3:
inorder(root);
break;
case 4:
preorder(root);
break;
case 5:
postorder(root);
break;
case 6:
exit(0);
default :
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
/* To insert a node in the tree */
void insert()
{
create();
if (root == NULL)
root = temp;
else
search(root);
}
/* To create a node */
void create()
{
117 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
int data;
printf("Enter data of node to be inserted : ");
scanf("%d", &data);
temp = (struct btnode *)malloc(1*sizeof(struct btnode));
temp->value = data;
temp->l = temp->r = NULL;
}
/* Function to search the appropriate position to insert the new node */
void search(struct btnode *t)
{
if ((temp->value > t->value) && (t->r != NULL))
/* value more than root node value insert at right */
search(t->r);
else if ((temp->value > t->value) && (t->r == NULL))
t->r = temp;
else if ((temp->value < t->value) && (t->l != NULL))
/* value less than root node value insert at left */
search(t->l);
else if ((temp->value < t->value) && (t->l == NULL))
t->l = temp;
}
/* recursive function to perform inorder traversal of tree */
void inorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display");
return;
}
118 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
if (t->l != NULL)
inorder(t->l);
printf("%d -> ", t->value);
if (t->r != NULL)
inorder(t->r);
}
/* To check for the deleted node */
void delete()
{
int data;
if (root == NULL)
{
printf("No elements in a tree to delete");
return;
}
printf("Enter the data to be deleted : ");
scanf("%d", &data);
t1 = root;
t2 = root;
search1(root, data);
}
/* To find the preorder traversal */
void preorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display");
return;
}
119 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
120 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
{
t1 = t;
search1(t->l, data);
}
else if ((data==t->value))
{
delete1(t);
}
}
/* To delete a node */
void delete1(struct btnode *t)
{
int k;
/* To delete leaf node */
if ((t->l == NULL) && (t->r == NULL))
{
if (t1->l == t)
{
t1->l = NULL;
}
else
{
t1->r = NULL;
}
t = NULL;
free(t);
return;
}
/* To delete node having one left hand child */
121 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
122 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
else
t1->l = t->r;
t == NULL;
free(t);
return;
}
/* To delete node having two child */
else if ((t->l != NULL) && (t->r != NULL))
{
t2 = root;
if (t->r != NULL)
{
k = smallest(t->r);
flag = 1;
}
else
{
k =largest(t->l);
flag = 2;
}
search1(root, k);
t->value = k;
}
}
/* To find the smallest element in the right sub tree */
int smallest(struct btnode *t)
{
t2 = t;
if (t->l != NULL)
123 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
{
t2 = t;
return(smallest(t->l));
}
else
return (t->value);
}
/* To find the largest element in the left sub tree */
int largest(struct btnode *t)
{
if (t->r != NULL)
{
t2 = t;
return(largest(t->r));
}
else
return(t->value);
}
OUTPUT :
OPERATIONS ---
1 - Insert an element into tree
2 - Delete an element from the tree
3 - Inorder Traversal
4 - Preorder Traversal
5 - Postorder Traversal
6 - Exit
Enter your choice : 1
Enter data of node to be inserted : 40
124 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
40
/\
/ \
20 60
/\ \
10 30 80
\
90
125 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
void main()
{
int choice;
char ans='N';
int key;
node *new_node,*root,*tmp,*parent;
126 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
node *get_node();
root=NULL;
clrscr();
switch(choice)
{
case 1:
do
{
new_node=get_node();
printf("nEnter The Element ");
scanf("%d",&new_node->data);
if(root==NULL) /* Tree is not Created */
root=new_node;
else
insert(root,new_node);
printf("nWant To enter More Elements?(y/n)");
ans=getch();
}while(ans=='y');
127 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
break;
case 2:
printf("nEnter Element to be searched :");
scanf("%d",&key);
tmp = search(root,key,&parent);
printf("nParent of node %d is %d",
tmp->data,parent->data);
break;
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()
{
node *temp;
temp=(node *)malloc(sizeof(node));
128 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
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);
}
if(new_node->data > root->data)
{
if(root->rchild==NULL)
root->rchild=new_node;
else
insert(root->rchild,new_node);
}
}
/*This function is for searching the node from binary Search Tree*/
node *search(node *root,int key,node **parent)
{
node *temp;
temp=root;
while(temp!=NULL)
{
129 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
if(temp->data==key)
{
printf("n The %d Element is Present",temp->data);
return temp;
}
*parent=temp;
if(temp->data>key)
temp=temp->lchild;
else
temp=temp->rchild;
}
return NULL;
}
130 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
printf("%d",temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}
/* This function displays the tree in postorder fashion */
void postorder(node *temp)
{
if(temp!=NULL)
{
postorder(temp->lchild);
postorder(temp->rchild);
printf("%d",temp->data);
}
}
OUTPUT :
Program For Binary Search Tree
1.Create
2.Search
3.Recursive Traversals
4.Exit
Enter your choice :1
Enter The Element 5
Do u Want To enter More Elements?(y/n) y
Enter The Element 12
Do u Want To enter More Elements?(y/n) y
Enter The Element 6
Do u Want To enter More Elements?(y/n) y
Enter The Element 3
131 | P a g e
KHYATI SCHOOL OF ENGINEERING
COMPUTER ENGINEERING
132 | P a g e