0% found this document useful (0 votes)
387 views

Data Structures Basic Programs

The document discusses key concepts related to algorithm analysis including: 1) Definitions of algorithm complexity measures like time complexity and space complexity which describe an algorithm's efficiency in terms of input size. 2) Common notations for describing time complexity like Big-O notation which provides asymptotic upper bounds. 3) Examples of algorithm time complexities including constant, logarithmic, linear, quadratic, and exponential functions of input size. 4) The document provides examples to illustrate algorithm complexity analysis and efficiency comparisons.

Uploaded by

Nishant Patel
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
387 views

Data Structures Basic Programs

The document discusses key concepts related to algorithm analysis including: 1) Definitions of algorithm complexity measures like time complexity and space complexity which describe an algorithm's efficiency in terms of input size. 2) Common notations for describing time complexity like Big-O notation which provides asymptotic upper bounds. 3) Examples of algorithm time complexities including constant, logarithmic, linear, quadratic, and exponential functions of input size. 4) The document provides examples to illustrate algorithm complexity analysis and efficiency comparisons.

Uploaded by

Nishant Patel
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 132

KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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.

o Types of Notations for Time Complexity

 Now we will discuss and understand the various notations used for Time
Complexity.

2|Page
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

 Big Oh denotes "fewer than or the same as" <expression> iterations.

 Big Omega denotes "more than or the same as" <expression> iterations.

 Big Theta denotes "the same as" <expression> iterations.

 Little Oh denotes "fewer than" <expression> iterations.

 Little Omega denotes "more than" <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

SUB CODE: 3330704 Data Structure

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

We express complexity using big-O notation. For a problem of size N:

o a constant-time method is "order 1": O(1)


o a linear-time method is "order N": O(N)

o a quadratic-time method is "order N squared": O(N2)

o Note :

o the big-O expressions do not have constants or low-order terms.

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 See below for an example.

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

SUB CODE: 3330704 Data Structure

 For example, consider T(N) = 3 * N2 + 5. We can show that T(N) is O(N2)


by choosing c = 4 and n0 = 2. This is because for all values of N greater than
2 : 3 * N2 + 5 <= 4 * N2

o T(N) is not O(N), because whatever constant c and value n0 you


choose, I can always find a value of N greater than n0 so that 3 * N2
+ 5 is greater than c * N.

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.

Notation Name Example

Determining if a number is even or odd;


constant
Calculating ; Using a constant-size lookup table

Number of comparisons spent finding an item


double
using interpolation search in a sorted array of uniformly
logarithmic
distributed values

Finding an item in a sorted array with a binary search or a


logarithmic balanced search tree as well as all operations in a Binomial
heap

fractional power Searching in a kd-tree

linear Finding an item in an unsorted list or a malformed tree


(worst case) or in an unsorted array; adding two n-bit
5|Page
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

integers byripple carry

Performing triangulation of a simple polygon using


Seidel's algorithm, or the union–find
algorithm (Note
n log-star n

linearithmic, Performing a fast Fourier


loglinear, or transform; heapsort, quicksort (best and average case),
quasilinear or merge sort

Multiplying two n-digit numbers by a simple


algorithm; bubble sort (worst case or naive
quadratic
implementation), Shell sort, quicksort (worst
case), selection sort or insertion sort

polynomial or Tree-adjoining grammar parsing;


algebraic maximum matching for bipartite graphs

L-notation or su Factoring a number using the quadratic sieve or number


b-exponential field sieve

Finding the (exact) solution to the travelling salesman


exponential problem using dynamic programming; determining if two
logical statements are equivalent using brute-force search

6|Page
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

Solving the traveling salesman problem via brute-force


search; generating all unrestricted permutations of a poset;
factorial
finding the determinant with expansion by minors;
enumerating all partitions of a set

o The statement is sometimes weakened to to derive simpler formulas for

asymptotic complexity. For any and , is a subset of for


any , so may be considered as a polynomial with some bigger order.

We can have three cases to analyze an algorithm:


1) Worst Case
2) Average Case
3) Best Case

Let us consider the following implementation of Linear Search.

#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

SUB CODE: 3330704 Data Structure

/* Driver program to test above functions*/


int main()
{
int arr[] = {1, 10, 30, 15};
int x = 30;
int n = sizeof(arr)/sizeof(arr[0]);
printf("%d is present at index %d", x, search(arr, n, x));
getchar();
return 0;
}
Worst Case Analysis (Usually Done)
 In the worst case analysis, we calculate upper bound on running time of an algorithm.
 We must know the case that causes maximum number of operations to be executed.
 For Linear Search, the worst case happens when the element to be searched (x in the above code)
is not present in the array.
 When x is not present, the search() functions compares it with all the elements of arr[] one by one.
 Therefore, the worst case time complexity of linear search would be .
Average Case Analysis (Sometimes done)
 In average case analysis, we take all possible inputs and calculate computing time for all of the
inputs.
 Sum all the calculated values and divide the sum by total number of inputs. We must know (or
predict) distribution of cases.
 For the linear search problem, let us assume that all cases are uniformly distributed (including the
case of x not being present in array).
 So we sum all the cases and divide the sum by (n+1). Following is the value of average case time
complexity.
Best Case Analysis (Bogus)
 In the best case analysis, we calculate lower bound on running time of an algorithm.

8|Page
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

 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.

 The number of operations in worst case is constant (not dependent on n).

 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

SUB CODE: 3330704 Data Structure

1.2 Develop simple program using pointer to a structure


PROGRAM :
#include <stdio.h>
#include <stdlib.h>
struct mystruct
{
int a;
};
typedef struct mystruct * pmystruct;
pmystruct getpstruct()
{
pmystruct temp=(pmystruct)malloc(sizeof(pmystruct*)) ;
return temp;
}
int main(int argc, char* argv[])
{
pmystruct pb= getpstruct() ;
pb->a = 8;
++pb->a;
printf ("The value of b->a is %i ",pb->a) ;
free(pb) ;
return 0;
}
OUTPUT :
The value of b 9

10 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

1.3 Implement array using row major order and column major order
PROGRAM :
#include <stdio.h>
#include <conio.h>
#define MAX 5

void insert ( int *, int pos, int num ) ;


void del ( int *, int pos ) ;
void reverse ( int * ) ;
void display ( int * ) ;
void search ( int *, int num ) ;

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 ) ;

printf ( "\nElements of Array: " ) ;


display ( arr ) ;

del ( arr, 5 ) ;
del ( arr, 2 ) ;
printf ( "\n\nAfter deletion: " ) ;
display ( arr ) ;

11 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

insert ( arr, 2, 222 ) ;


insert ( arr, 5, 555 ) ;
printf ( "\n\nAfter insertion: " ) ;
display ( arr ) ;

reverse ( arr ) ;
printf ( "\n\nAfter reversing: " ) ;
display ( arr ) ;

search ( arr, 222 ) ;


search ( arr, 666 ) ;
getch( ) ;
}
/* inserts an element num at given position pos */
void insert ( int *arr, int pos, int num )
{
/* shift elements to right */
int i ;
for ( i = MAX - 1 ; i >= pos ; i-- )
arr[i] = arr[i - 1] ;
arr[i] = num ;
}
/* deletes an element from the given position pos */
void del ( int *arr, int pos )
{
/* skip to the desired position */
int i ;
for ( i = pos ; i < MAX ; i++ )

12 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

arr[i - 1] = arr[i] ;
arr[i - 1] = 0 ;
}

/* reverses the entire array */


void reverse ( int *arr )
{
int i ;
for ( i = 0 ; i < MAX / 2 ; i++ )
{
int temp = arr[i] ;
arr[i] = arr[MAX - 1 - i] ;
arr[MAX - 1 - i] = temp ;
}
}
/* searches array for a given element num */
void search ( int *arr, int num )
{
/* Traverse the array */
int i ;
for ( i = 0 ; i < MAX ; i++ )
{
if ( arr[i] == num )
{
printf ( "\n\nThe element %d is present at %dth position.", num, i + 1 ) ;
return ;
}
}

13 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

555
After reversing:
555
14
13
222
11

15 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

1.4 Implement Sequential search algorithms


PROGRAM :
# include<stdio.h>
#include<conio.h>

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

SUB CODE: 3330704 Data Structure

void display(int list[], int n)


{
int i;
for(i = 0 ; i < n ; i++)
{
printf(" %d", list[i]);
}
}
input(int list[], int number, int key)
{
int i;
key = 30;
printf("Input the number of elements in the list:");
number = 20;
for(i = 0 ; i < 20; i++)
{
list[i] = rand() %100;
}
printf("\n Element to be searched: %d", key);
search = key;
return number;
}
void main()
{
int number, key, list[200];
clrscr();
number = input( list, number, key);

17 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

1.5 Implement Binary search algorithms


PROGRAM :
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],n,i,j,temp;
int beg,end,mid,target;
clrscr();
printf(“enter the total numbers: “);
scanf(“%d”, &n);
printf(“enter the array elements: “);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j+1]<a[j])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf(“the sorted numbers are: “);
for(i=0;i<n;i++)
printf(“%4d”,a[i]);
19 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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
Lenlen+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

SUB CODE: 3330704 Data Structure

OUTPUT:
Enter String : Mansi
Length of String : 5
Algorithm for copy string:
Step1: [initilization]
Str1  null
i0
j0
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

SUB CODE: 3330704 Data Structure

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]
Str3null
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)kk+1
Step3 : [append str2 string in to str3]
While(j<>len(str2))repeat
(a)str3[k] str2[j]
(b)j j+1
(c)kk+1
Step4 : [print the string after concatenation operation performed]
Write(“str3”)

24 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

OUTPUT:-
Your string is: Mansi Shah
Algorithm for string comparision:-
Step1 : [Initilization]
i 0
j0
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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

}
}
}
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]
i0
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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

Printf(“Your original string is %s”,str1);


Printf(“Your original string is %s”,str2);
getch();
}
OUTPUT:-
Enter your string: computer
Enter your string position: 3
Enter the no of char: 8
Your original string is computer
Your substring is puter.

30 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

}
}
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

SUB CODE: 3330704 Data Structure

3.display
4.exit
enter your choice : 3
op->11

37 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

3.2 Implement recursive functions


PROGRAM :
/*Program to find the number of nodes in the linked list using recursion */
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
/* structure containing a data part and link part */
struct node
{
int data ;
struct node *link ;
};
void append ( struct node **, int ) ;
int length ( struct node * ) ;
void main( )
{
struct node *p ;
p = NULL ; /* empty linked list */
append ( &p, 1 ) ;
append ( &p, 2 ) ;
append ( &p, 3 ) ;
append ( &p, 4 ) ;
append ( &p, 5 ) ;
clrscr( ) ;
printf ( "Length of linked list = %d", length ( p ) ) ;
}
/* adds a node at the end of a linked list */
void append ( struct node **q, int num )
{

38 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

struct node *temp ;


temp = *q ;

if ( *q == NULL ) /* if the list is empty, create first node */


{
*q = malloc ( sizeof ( struct node ) ) ;
temp = *q ;
}
else
{
/* go to last node */
while ( temp -> link != NULL )
temp = temp -> link ;

/* add node at the end */


temp -> link = malloc ( sizeof ( struct node ) ) ;
temp = temp -> link ;
}
/* assign data to the last node */
temp -> data = num ;
temp -> link = NULL ;
}
/* counts the number of nodes in a linked list */
int length ( struct node *q )
{
static int l ;
/* if list is empty or if NULL is encountered */
if ( q == NULL )
return ( 0 ) ;

39 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

3.3 Implement insert, delete algorithms of queue using array


Algorithm
QINSERT (Q,F,R,N,Y)
Step 1 : if R ≥ N
then Write (‘OVERFLOW’).
Return.
Step 2 : R ← R+1.
Step 3 : Q[R] ← Y
Step 4 : if F=0
then F ← 1
Return.
QDELETE (Q,F,R)
Step 1 : if F = 0
then Write (‘UNDERFLOW’).
Return(0).
Step 2 : Y ← Q[F]
Step 3 : if F=R
then F ← R ← 0
else F ← F + 1.
Step 4 : Return(Y).
PROGRAM:
#include<stdio.h>
#include<conio.h>

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

Press p for display


Press e for exit
enter your choice : p
Displaying Queue : 22

46 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

3.4 Implement insert, delete algorithms of circular queue


Algorithm
PUSH(S,Front,Rear,X)
Step 1: [check for circular queue”over flow”]
If Front=1 and Rear=n
Then
Write(“circular queue is overflow”)
Exit
Step 2: [insert elements in a circular queue]
Else if=0
Front<-1
Rear<-1
S[Rear]<-X
Step 3: [check if the rear at the end of circular queue)
Else if Rear=n
Rear<-1
S[Rear]<-x
Step 4: [insert the elements in circular queue]
Else
Rear<Rear+1
S[Rear]<-X
Step 5: [Finished]
POP(S,Front,Rear,X)
Step 1: [check for “underflow”]
If front=0
Then write (“circular queue is underflow”)
Exit
Step 2: [remove an elements from circular queue]
X<-S[Front]

47 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

Step 3: [print the POP elements]


Write(“X”)
Step 4: [chek whether circular queue is empty or not]
If (front=Rear)
Then
Front<-0
Rear<-0
Step 5: [check front pointer position]
Else if front=size
Front<-1
Else
Front<-front+1
Step 6: [Finished]
Exit
PROGRAM :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define SIZE 5
void push(int *CQUEUE,int x);
void pop(int *CQUEUE);
void display(int *CQUEUE);
int FRONT=-1;
int REAR=-1;
int CQUEUE[SIZE];
void main()
{
int x,ch;
clrscr();

48 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

printf("Circular Queue is Overflow");


else
{
if (REAR==-1 && FRONT==-1)
{
FRONT=0;
REAR=0;
}
else if (REAR==SIZE-1 && FRONT!=0)
REAR=0;
else
REAR=REAR+1;
CQUEUE[REAR]=x;
}
}

void pop(int *CQUEUE)


{
if(FRONT==-1)
printf("Circular Queue is Underflow");
else
{
printf("Deleted Element is %d\n",CQUEUE[FRONT]);
if(FRONT==REAR)
{
FRONT=-1;
REAR=-1;
}
else

50 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

{
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 :

Select Your Choice:


51 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

(1) PUSH

(2) POP

(3) Display

Enter Your Choice

22 5 11 14 17

52 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

}
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

SUB CODE: 3330704 Data Structure

{
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

SUB CODE: 3330704 Data Structure

7.DELETE MIDDLE NODE(USER'S CHOICE)


8.DISPLAY
9 EXIT
ENTER YOUR CHOICE : 2
20
30
40
50
60
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
7.DELETE MIDDLE NODE(USER'S CHOICE)
8.DISPLAY
9 EXIT
ENTER YOUR CHOICE : 10

61 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

4.3 Implement insertion of node in sorted linked list


PROGRAM :
#include <stdio.h>
#include<stdio.h>
#define NULL 0
struct linked_list
{
int number;
struct linked-list *next;
};
typedef struct linked_lit node;
main()
{
int n;
node *head;
void create(node *p);
node *insert(node *p, int n);
void print(node *p);
head = (node *)malloc(sizeof(node));
create(head);
printf(“\n”);
printf(“Original list: “);
print(head);
printf(“\n\n”);
printf(“Input number to be inserted: “);
scanf(“%d”, &n);

head = inert(head,n);
printf(“\n”);

62 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

printf(“New list: “);


print(head);
}
void create(node *list)
{
printf(“Input a number \n”);
printf(“(type –999 at end): “);
scanf(“%d”, &list->number);

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

Input number to be inserted : 25


New list: 10-->20-->25-->30-->40-->-999

65 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

struct node *next;


};
void generate(struct node **, int);
void search(struct node *, int, int);
void delete(struct node **);
int main()
{
struct node *head;
int key, num;

printf("Enter the number of nodes: ");


scanf("%d", &num);
generate(&head, num);
printf("\nEnter key to search: ");
scanf("%d", &key);
search(head, key, num);
delete(&head);
}
void generate(struct node **head, int num)
{
int i;
struct node *temp;

for (i = 0; i < num; i++)


{
temp = (struct node *)malloc(sizeof(struct node));
temp->a = rand() % num;
printf("%d ", temp->a);
if (*head == NULL)

67 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

{
*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

SUB CODE: 3330704 Data Structure

*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

SUB CODE: 3330704 Data Structure

STEP 6 : Display the total count of nodes


OUTPUT count
STEP 7 : Stop
PROGRAM :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}
*head,*temp;
void insert_data(int value)
{
struct node *var;
temp=head;
var=(struct node *)malloc(sizeof(struct node));
var->data=value;
if(head==NULL)
{
head=var;
head->next=NULL;
}
else
{
while(temp->next!=NULL)
{
temp=temp->next;

70 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

}
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

SUB CODE: 3330704 Data Structure

int i,value;
char ch='y';
head=NULL;

printf(" 1.) Insert node");


printf("\n 2.) display the list");
printf("\n 3.) count number of nodes");
printf("\n 4.) exit");
while(ch=='y')
{
printf("\nChoose to do operation :");
scanf("%d",&i);
switch(i)
{
case 1 :
{
printf("\nEnter the data to be inserted in node ");
scanf("%d",&value);
insert_data(value);
//display();
break;
}
case 2 :
{
display();
break;
}
case 3 :
{

72 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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]

(A)[If there is no node].


If (first=NULL)
Then
tmp<-avail
avail<- link[avail]
prev[tmp]<-NULL
1). [Assign info portion of tmp to x]
Info[tmp]<-x
2).[set link of tmp].
Next[tmp]<-NULL.

(B).[ If there is any node in list]


1).[Create a node].
Tmp<-avail
Avail<-link[avail]
2).[Assign data to node]
Info[tmp]<-x
3)[Set link of tmp]
Next[tmp]<-(first)
Prev(first)<-NULL.

STEP 2: [finished]
75 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

Return

ALGORITHM FOR INSERT A NODE AT END:


Alorithm:- Doubly_insend(first,x,next,prev)
STEP 1: [Create a node and set data and link portion]
a) [Create node]
tmp<- avail
avail<-link[avail]
b) [Assign data]
Info[tmp]<-x
c) [Set next portion to NULL]
Next[tmp]<-NULL
STEP 2: [Ifd ther is no node]
If(first=NULL)
Then
First<-tmp
Prev[first]<-NULL
STEP 3:-[If node exist]
a) [Assign address of first node]
Temp<-first
b) [Traverse the list until last node is reached]
Repeat while(link(tmp)< >NULL)
Temp<-link[tmp]
c) [Set link of last node to new node]
Prev[tmp]<-temp
Next[tmp]<-NULL
STEP4:[finished]
Return
ALGORITHM FOR INSERT A NODE AT ANY SPECIFIC LOCATION:

76 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

Alorithm:- Doubly_insloc(first,x,next,prev)

STEP 1: [Read location]


Read N
STEP 2: [If location is 1]
If(N=1)
Then
A) [Create new node]
tmp<- avail
avail<- link[avail]
B) [Asign INFO portion to X]
INFO[tmp]<-X
C) [for first node PREV pointer always NULL]
Prev[tmp]<-NULL
D) [Check whether any node exist or not]
If(First=NULL)
Then
next[tmp]<-first
prev[first]<-tmp
E) [Move the first pointer to tmp ]
First<-tmp
STEP 3:[If location is N]
A) [Assign first pointer to temp]
temp<-first
B) [Reach at desired location by traversing a list]
Temp<-next[temp]
C) [Create new node]
tmp<-avail

77 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

avail<-link[avail]

D) [Assign INFO portion of tmp to X]


INFO[tmp]<-X
E) [Assign the next & prev portion of tmp]
Prev[tmp]<- temp
Next[tmp]<-next[temp]
F) [Assign the next portion of tmp]
Next[tmp]<-tmp
G) [Assign prev portion of nodes whose address is next portion of tmp]
Prev[next(tmp)]<-tmp
STEP 4: [Finished]
Return.
PROGRAM :
#include<conio.h>
#include<stdio.h>
struct doubly
{
struct doubly *front;
struct doubly *back;
int i;
};
void main()
{
struct doubly *head=0;
struct doubly *last=0;
struct doubly *p=0;
struct doubly *temp=0;
int ch,intch,user,cnt=0,t,add;

78 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

{
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

SUB CODE: 3330704 Data Structure

}
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

SUB CODE: 3330704 Data Structure

4.6 Implement searching of a node and counting no of node algorithms in doubly


linked list.
ALGORITHM FOR SEARCH A NODE:
Searching(first,x)
Step1 [initialization]
Count=0
Flag=0
Temp=first
Step2 repeat while(info[temp]!=NULL)
(1) Temp=next[temp]
(2) Flag=flag+1
Step3 if(info[temp]=x) then
Write(“item found at position flag”)
Count=1
Step4 if(count=0)
Then write(“item not found”)
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()
84 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

{
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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

OUTPUT :
total number of nodes= 3

87 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

#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

SUB CODE: 3330704 Data Structure

}
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

SUB CODE: 3330704 Data Structure

for (int j = i+1; j < n; j++)


if (a[j] < a[min]) min = j;
swap(a[i], a[min]);
}
}

template < class Object>


void swap( Object &lhs, Object &rhs )
{
Object tmp = lhs;
lhs = rhs;
rhs = tmp;
}
PROGRAM :
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,t;
clrscr();
printf("\n\n Selection Sort");
printf("\n\n Enter Values:");
for(i=0;i<10;i++)
{
scanf("\n%d",&a[i]);
}
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)

91 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

{
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

SUB CODE: 3330704 Data Structure

1
2
3
4
5
6
9
25
56
60

93 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

5.2 Implement Quick Sort


ALGORITHM FOR QUICK SORT :
The quick-sort algorithm consists of the following three steps:
1. Divide: Partition the list.
To partition the list, we first choose some element from the list for which we hope about half the elements
will come before and half after. Call this element the pivot.
Then we partition the elements so that all those with values less than the pivot come in one sublist and all
those with greater values come in another.
2. Recursion: Recursively sort the sublists separately.
3. Conquer: Put the sorted sublists together.
PROGRAM :
#include <stdio.h>
#include <stdlib.h>
#define maxsize 4
int A[maxsize];
void quicksort(int a, int b)
{
int rtidx=0,ltidx=0,k=a,l=0,pivot;
int leftarr[maxsize],rtarr[maxsize];
pivot=A[a];
if(a==b)
return;
while(k<b)
{
++k;
if(A[k]<A[a])
{
leftarr[ltidx]=A[k];
ltidx++;

94 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

}
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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

5.3 Implement Insertion sort, Shell sort algorithm


ALGORITHM FOR INSERTION SORT :
template <class Item>
void insertionSort(Item a[], int n)
{
for (int i = 1; i < n; i++)
{
Item tmp = a[i];

for (int j=i; j>0 && tmp < a[j-1]; j--)


a[j] = a[j-1];
a[j] = tmp;
}
}
PROGRAM :
#include<stdio.h>
int main()
{
int i,j,num,temp,a[20];
printf("Enter total elements: ");
scanf("%d",&num);

printf("Enter %d elements: ",num);


for(i=0;i<num;i++)
scanf("%d",&a[i]);

for(i=1;i<num;i++){
temp=a[i];
j=i-1;

98 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

while((temp<a[j])&&(j>=0)){
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}

printf("After Sorting: ");


for(i=0;i<num;i++)
printf("%d",a[i]);

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]

# Start with the largest gap and work down to a gap of 1


foreach (gap in gaps)
{
# Do a gapped insertion sort for this gap size.
# The first gap elements a[0..gap-1] are already in gapped order
# keep adding one more element until the entire array is gap sorted
for (i = gap; i < n; i += 1)
{

99 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

# add a[i] to the elements that have been gap sorted


# save a[i] in temp and make a hole at position i
temp = a[i]
# shift earlier gap-sorted elements up until the correct location for a[i] is found
for (j = i; j >= gap and a[j - gap] > temp; j -= gap)
{
a[j] = a[j - gap]
}
# put temp (the original a[i]) in its correct location
a[j] = temp
}

}
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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

How many elements are there? 5


a[0]=23
a[1]=21
a[2]=11
a[3]=5
a[4]=8

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

SUB CODE: 3330704 Data Structure

5.4 Implement Merge Sort algorithm


ALGORITHM FOR MERGE SORT :
const int MAX_SIZE = maximum-number-of-items-in-array;
void merge(DataType theArray[], int first, int mid, int last) {
DataType tempArray[MAX_SIZE]; // temporary array
int first1 = first; // beginning of first subarray
int last1 = mid; // end of first subarray
int first2 = mid + 1; // beginning of second subarray
int last2 = last; // end of second subarray
int index = first1; // next available location in tempArray
for ( ; (first1 <= last1) && (first2 <= last2); ++index) {
if (theArray[first1] < theArray[first2]) {
tempArray[index] = theArray[first1];
++first1;
}
else {
tempArray[index] = theArray[first2];
++first2;
}}
// finish off the first subarray, if necessary
for (; first1 <= last1; ++first1, ++index)
tempArray[index] = theArray[first1];
// finish off the second subarray, if necessary
for (; first2 <= last2; ++first2, ++index)
tempArray[index] = theArray[first2];
// copy the result back into the original array
for (index = first; index <= last; ++index)
theArray[index] = tempArray[index];
} // end merge

103 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

void mergesort(DataType theArray[], int first, int last) {


if (first < last) {
int mid = (first + last)/2; // index of midpoint
mergesort(theArray, first, mid);
mergesort(theArray, mid+1, last);

// merge the two halves


merge(theArray, first, mid, last);
}
} // end mergesort
PROGRAM :
#include<stdio.h>
#include<conio.h>
int merge_sort( int , int *, int , int *, int * );
int bubble_sort(int , int *);

/* 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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

for(ch = 0; ch < k; ch++)


printf(" %d", result_list[ch]);
}
}
/* checks if size of list_b larger than list_a copy rest of the elements of list_b into result_list */
Else if(j < m)
{
for(l = j; l<m; l++)
{
result_list[k] = list_b[j];
j++;
k++;
printf("\n");
for(ch = 0; ch < k; ch++)
printf(" %d", result_list[ch]);
}
}
return (k);
}
/* function main */
void main()
{
int list_a[100],list_b[100];
int result[200];
int n, m, k, i;

printf("\n Input the number of elements of list_a: ");


scanf("%d", &n);

107 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

for(i = 0; i<n ; i++)


{
printf("\n Input the element: %d: ", i+1);
scanf("%d", &list_a[i]);
}
/* Sort the elements of list_a */
bubble_sort(n, list_a);
/* End of sorting */
printf("\n Input the number of elements of list_b:");
scanf("%d", &m);
for(i = 0 ; i< m ; i++)
{
printf("\n Input the element: %d: ", i+1);
scanf("%d", &list_b[i]);
}
/* Sort the elements of list_b */
bubble_sort(m, list_b);
/* End of sorting */
k = merge_sort( n, list_a, m , list_b, result);
printf("\n Duplicates are : %d", m+n-k);
printf("\n");

printf("\n Sorted list is as follows:\n");


for(i = 0 ; i< k ; i++)
{
printf(" %d", result[i]);
}
}
OUTPUT :

108 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

o useful if we don't know much about the keys

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

struct node * buildtree ( int ) ;


void inorder ( struct node * ) ;

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( ) ;
}

struct node * buildtree ( int index )


{
struct node *temp = NULL ;
if ( index != -1 )
{
temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
temp -> left = buildtree ( lc[index] ) ;
temp -> data = arr[index] ;
temp -> right = buildtree ( rc[index] ) ;
}
return temp ;

113 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

}
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

SUB CODE: 3330704 Data Structure

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])

1: if x = nil then return (“Empty Tree”)


2: y ← x
3: while right[y] 6= nil do y ← right[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

SUB CODE: 3330704 Data Structure

void preorder(struct btnode *t);


void postorder(struct btnode *t);
void search1(struct btnode *t,int data);
int smallest(struct btnode *t);
int largest(struct btnode *t);

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

printf("%d -> ", t->value);


if (t->l != NULL)
preorder(t->l);
if (t->r != NULL)
preorder(t->r);
}
/* To find the postorder traversal */
void postorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display ");
return;
}
if (t->l != NULL)
postorder(t->l);
if (t->r != NULL)
postorder(t->r);
printf("%d -> ", t->value);
}
/* Search for the appropriate position to insert the new node */
void search1(struct btnode *t, int data)
{
if ((data>t->value))
{
t1 = t;
search1(t->r, data);
}
else if ((data < t->value))

120 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

{
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

SUB CODE: 3330704 Data Structure

else if ((t->r == NULL))


{
if (t1 == t)
{
root = t->l;
t1 = root;
}
else if (t1->l == t)
{
t1->l = t->l;
}
Else
{
t1->r = t->l;
}
t = NULL;
free(t);
return;
}
/* To delete node having right hand child */
else if (t->l == NULL)
{
if (t1 == t)
{
root = t->r;
t1 = root;
}
else if (t1->r == t)
t1->r = t->r;

122 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

{
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

SUB CODE: 3330704 Data Structure

Enter your choice : 1


Enter data of node to be inserted : 20

Enter your choice : 1


Enter data of node to be inserted : 10

Enter your choice : 1


Enter data of node to be inserted : 30

Enter your choice : 1


Enter data of node to be inserted : 60

Enter your choice : 1


Enter data of node to be inserted : 80

Enter your choice : 1


Enter data of node to be inserted : 90

Enter your choice : 3


10 -> 20 -> 30 -> 40 -> 60 -> 80 -> 90 ->

40
/\
/ \
20 60
/\ \
10 30 80
\
90

125 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

6.3 Implement searching algorithm in binary search tree.


ALGORITHM :

Step 1: [If ROOT = NULL then


Return(Tree is empty)
Step 2: If X=ROOT->INFO then
PROGRAM :
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>

typedef struct BST


{
int data;
struct BST *lchild,*rchild;
}node;

void insert(node *,node *);


void inorder(node *);
void preorder(node *);
void postorder(node *);
node *search(node *,int,node **);

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

SUB CODE: 3330704 Data Structure

node *get_node();
root=NULL;
clrscr();

printf("nProgram For Binary Search Tree ");


do
{
printf("n1.Create");
printf("n2.Search");
printf("n3.Recursive Traversals");
printf("n4.Exit");
printf("nEnter your choice :");
scanf("%d",&choice);

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

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;
}

/*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);
}
}
/*This function displays the tree in preorder fashion*/
void preorder(node *temp)
{
if(temp!=NULL)
{

130 | P a g e
KHYATI SCHOOL OF ENGINEERING

COMPUTER ENGINEERING

SUB CODE: 3330704 Data Structure

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

SUB CODE: 3330704 Data Structure

Do u Want To enter More Elements?(y/n) n


1.Create
2.Search
3.Recursive Traversals
4.Exit
Enter your choice :3
The Inorder display : 3 5 6 12
The Preorder display : 5 3 12 6
The Postorder display : 3 6 12 5
1.Create
2.Search
3.Recursive Traversals
4.Exit
Enter your choice :2
Enter Element to be searched : 3
The 20 Element is Present
Parent of node 3 is 5

132 | P a g e

You might also like