0% found this document useful (0 votes)
160 views63 pages

Data Structure & Analysis Maual

The document is a manual on data structures and analysis submitted by a computer engineering student to their professor. It contains 16 chapters covering various data structures like arrays, stacks, queues, linked lists, and structures implemented using arrays and pointers. It also includes sample programs for traversing, searching, and sorting arrays. The manual provides online resources for additional reference materials on data structures and algorithms.

Uploaded by

Nayab Syed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
160 views63 pages

Data Structure & Analysis Maual

The document is a manual on data structures and analysis submitted by a computer engineering student to their professor. It contains 16 chapters covering various data structures like arrays, stacks, queues, linked lists, and structures implemented using arrays and pointers. It also includes sample programs for traversing, searching, and sorting arrays. The manual provides online resources for additional reference materials on data structures and algorithms.

Uploaded by

Nayab Syed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Manual

Of
Data Structure and Analysis

SUBMITTED TO:

Engr. Muhammad Baqer

SUBMITTED BY:

Roll No.
Computer Engineering
3rd Semester

UNIVERSITY COLLEGE OF ENGINEERING & TECHNOLOGY


BAHAUDDIN ZAKARIYA UNIVERSITY,
MULTAN

Umair Page 1
Contents
Sr.No Programs Page
1 Array
2 Bubble Sort by using Array
3 Linear Search by using Array
4 Binary Search by using Array
5 Largest number by using Array
6 Traverse by using Array
7 Stack by using Array
8 Queue by using Array
9 Array by using pointer
10 Bubble Sort by using pointer
11 Linear Search by using pointer
12 Binary Search by using pointer
13 Traverse by using Pointer
14 Stack by using Pointer
15 Queue by using pointer
16 Structure
17 Structure to Array
18 Structure to Pointer
19 Structure to Function
20 Link List
21 Dynamic Memory Allocation

Online resources
Site Location Description
Student Resources
Companion www.data structures and Link
algorithms.com /schaum series Instructor resources
Website
Link
http://www.scribd.com/doc/22206747/Lec1- Solution manual, slides &
Instructor Introduction-to-Data-Structure-and- other useful documents.
resources center Algorithms

(IRC)

Umair Page 2
Practical # 1

Array:
Operations on array
1- Traversing: means to visit all the elements of the array in an operation is called
traversing.
2- Insertion: means to put values into an array.
3- Deletion / Remove: to delete a value from an array.
4- Sorting: Re-arrangement of values in an array in a specific order (Ascending /
Descending) is called sorting.
5- Searching: The process of finding the location of a particular element in an array is
called searching.

Algorithm:
(Traverse a Linear Array) Here LA is a Linear array with lower boundary LB and upper
boundary UB. This algorithm traverses LA applying an operation Process to each element of LA.
1. [Initialize counter.] Set K=LB.
2. Repeat Steps 3 and 4 while KUB.
3. [Visit element.] Apply PROCESS to LA[K].
4. [Increase counter.] Set k=K+1.
[End of Step 2 loop.]
5. Exit.

Program:

Input

#include<iostream>
using namespace std;

main()

Umair Page 3
{

cout<<" \n";
cout<<" :p Bubble Sorting :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) UmairBashir :) \n";
cout<<" \n\n";

int first[20], second[20], c, n;

cout << "Enter the number of elements in the array ";


cin >> n;

cout << "Enter elements of first array " << endl;

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


cin >> first[c];

cout << "Enter elements of second array " << endl;

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


cin >> second[c];

cout << "Sum of elements of two arrays " << endl;

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


cout << first[c] + second[c] << endl;

return 0;

Umair Page 4
Output

Umair Page 5
Practical # 2
Bubble Sort:
The technique we use is called Bubble Sort because the bigger value gradually bubbles their
way up to the top of array like air bubble rising in water, while the small values sink to the
bottom of array. This technique is to make several passes through the array. On each pass,
successive pairs of elements are compared. If a pair is in increasing order (or the values are
identical), we leave the values as they are. If a pair is in decreasing order, their values are
swapped in the array.

Algorithm:
(Bubble Sort) BUBBLE (DATA, N) Here DATA is an Array with N elements. This algorithm
sorts the elements in DATA.
1. for pass=1 to N-1.
2. for (i=0; i<= N-Pass; i++)
3. If DATA[i]>DATA[i+1], then: Interchange DATA[i] and DATA[i+1].
[End of If Structure.]
[End of inner loop.]
[End of Step 1 outer loop.]
4. Exit.

Program:

Input

#include <iostream>
#define SIZE 6
using namespace std;

voidBubbleSort(int A[],int N);


int main()

Umair Page 6
cout<<" \n";
cout<<" :p Bubble Sorting :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) UmairBashir :) \n";
cout<<" \n\n";

int a[SIZE]= {22,42,35,2,51,16};


int i;

cout<< "The elements of the array before sorting\n";


for (i=0; i<= SIZE-1; i++) cout<< a[i]<<",\n ";

BubbleSort(a ,SIZE);

cout<< "\n\nThe elements of the array after sorting\n";


for (i=0; i<= SIZE-1; i++)

cout<< a[i]<<",\n ";


return 0;

voidBubbleSort(int A[ ], int N)

for (int pass=2; pass<= N-1; pass++)

for (int i=0; i<= SIZE-pass; i++)

if(A[i] <A[i+1])

int hold =A[i];


A[i]=A[i+1];
A[i+1]=hold;

}
}
}
}

Umair Page 7
Output

Umair Page 8
Practical # 3
Linear search:
The linear search compares each element of the array with the search key until the search key is
found. To determine that a value is not in the array, the program must compare the search key to
every element in the array. It is also called Sequential Search because it traverses the data
sequentially to locate the element.

Algorithm:

(Linear Search) LINEAR (A, SKEY) Here A is a Linear Array with N elements and SKEY is a
given item of information to search. This algorithm finds the location of SKEY in A and if
successful, it returns its location otherwise it returns -1 for unsuccessful.
1. Repeat for i = 0 to N-1
2. if( A[i] = SKEY) return i [Successful Search]
[ End of loop ]
3. return -1 [Un-Successful]
4. Exit.

Program:

Input
#include <iostream>
using namespace std;

intconst N=10;
intLinearSearch(int [ ], int); // Function Prototyping
int main()

cout<<" \n";
cout<<" :p Linear Search :p \n";

Umair Page 9
cout<<" PROGRAM BY \n";
cout<<" :) UmairBashir :) \n";
cout<<" \n\n";

int A[N]= {9, 4, 5, 1, 7, 78, 22, 15, 96, 45}, Skey, LOC;

cout<<" Enter the Search Key\n";


cin>>Skey;

LOC = LinearSearch( A, Skey); // call a function

if(LOC == -1)
cout<<" The search key is not in the array\n Un-Successful Search\n";

else
cout<<" The search key "<<Skey<< " is at location "<<LOC<<endl;

return 0;

intLinearSearch (int b[ ], intskey) // function definition

int i;
for (i=0; i<= N-1; i++) if(b[i] == skey) return i;
return -1;

Umair Page 10
Output

Umair Page 11
Practical # 4
Binary search:
It is useful for the large sorted arrays. The binary search algorithm can only be used with sorted
array and eliminates one half of the elements in the array being searched after each comparison.
The algorithm locates the middle element of the array and compares it to the search key. If they
are equal, the search key is found and array subscript of that element is returned. Otherwise the
problem is reduced to searching one half of the array.

Algorithm:

(Binary Search) Here A is a sorted Linear Array with N elements and SKEY is a given item of
information to search. This algorithm finds the location of SKEY in A and if successful, it
returns its location otherwise it returns -1 for unsuccessful.
BinarySearch (A, SKEY)
1. [Initialize segment variables.]
Set START=0, END=N-1 and MID=INT((START+END)/2).
2. Repeat Steps 3 and 4 while START END and A[MID]SKEY.
3. If SKEY<A[MID]. Then
Set END=MID-1.
Else Set START=MID+1.
[End of If Structure.]
4. Set MID=INT((START +END)/2).
[End of Step 2 loop.]
5. If A[MID]= SKEY then
Set LOC= MID
Else: Set LOC = -1
[End of IF structure.]
6. return LOC and Exit

Program:

Input
#include <iostream>
using namespace std;
#define N 10

Umair Page 12
int Binary Search( int [ ], int);
int main()

cout<<" \n";
cout<<" :p Binary Search :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) UmairBashir :) \n";
cout<<" \n\n";

int A[N]= {3, 5, 9, 11, 15, 17, 22, 25, 37, 68}, SKEY, LOC;

cout<<" Enter the Search Key\n ";


cin>>SKEY;

LOC = BinarySearch(A, SKEY);

if(LOC == -1)
cout<<" The search key is not in the array\n";

else
cout<<" The search key "<<SKEY <<" is at location "<<LOC<<endl;
return 0;

intBinarySearch (int A[], intskey)

int START=0, END= N-1, MID=int((START+END)/2), LOC;


while(START <= END && A[MID] != skey)

if(skey< A[MID])
END = MID - 1;

else
START = MID + 1;
MID=int((START+END)/2);

Umair Page 13
{

if(A[MID] == skey)
LOC=MID;

else LOC= -1;


return LOC;

}
}

Output

Umair Page 14
Practical # 5
Largest Number:
It is useful for the large sorted arrays. The larger number algorithm can only be used with sorted
array and use all the elements in the array being searched after each comparison. The algorithm
locates the larger element of the array and compares it to the other elements. If it is larger, the
search key is found and array subscript of that element is returned. Otherwise the problem is
reduced to searching all the elements of the array.

Algorithm:

FindLargest
Input:A list of positive integers
1. Set Largest to 0
2. while (more integers)
if (the integer is greater than Largest)
then
Set largest to the value of the integer
End if
End while
3. Return Largest
End

Program:

Input
#include<iostream>
using namespace std;

main()
{

cout<<" \n";
cout<<" :p Largest Number :p \n";
cout<<" PROGRAM BY \n";

Umair Page 15
cout<<" :) UmairBashir :) \n";
cout<<" \n\n";

int array[10]={1,0,6,4,-5,3,-1,3,9,8};

cout<<"\n The contents of the array are : "<<endl;


cout<<"\n Elements :"<<"\t\t Value:"<<endl;

for(int i=0; i<10; i++)

cout<<"\t"<<" array ["<<i<<"]"<<"\t\t"<<array[i]<<endl;

intlargest_number=array[0];
for(int j=0; j<10; j++)

if(array[j]>largest_number)
largest_number=array[j];

cout<<"\n The largest number of the array is = "<<largest_number<<endl;


return 0;

Umair Page 16
Output

Umair Page 17
Practical # 6
traverse:
It means processing or visiting each element in the array exactly once;
Let A is an array stored in the computers memory. If we want to display the contents of A, it
has to be traversed i.e. by accessing and processing each element of A exactly once.

Algorithm:

(Traverse a Linear Array) Here LA is a Linear array with lowerboundary LB and upper
boundary UB. This algorithm traverses LAapplying an operation Process to each element of LA.

1. [Initialize counter.] Set K=LB.


2. Repeat Steps 3 and 4 while KUB.
3. [Visit element.] Apply PROCESS to LA[K].
4. [Increase counter.] Set k=K+1.
[End of Step

Program:

Input

#include <iostream>
#define size 10 // another way intconst size = 10
using namespace std;

int main()

cout<<" \n";
cout<<" :p Traverse :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) UmairBashir :) \n";
cout<<" \n\n";
Umair Page 18
int x[10]={4,3,7,-1,7,2,0,4,2,13}, i, sum=0,LB=0, UB=size;
floatav;
for(i=LB;i<UB;i++)

sum = sum + x[i];

}
av = (float) sum/size;
cout<<"The average of the numbers=" <<av<<endl;
return 0;

Output

Umair Page 19
Practical # 7
Stack:
A stack is a list with the restriction that insertions and deletions can be performed in only one
position, namely, the end of the list, called the top.
The fundamental operations on a stack are push, which is equivalent to an insert, and pop, which
deletes the most recently inserted element. The most recently inserted element can be examined
prior to performing a pop by use of the top routine. A pop or top on an empty stack is generally
considered an error in the stack ADT. On the other hand, running out of space when performing
a push is an implementation limit but not an ADT error.

Algorithm:

1. [STACK already filled?]


If TOP=STACKSIZE-1, then:
Print: OVERFLOW / Stack Full, and Return.
2. Set TOP:=TOP+1. [Increase TOP by 1.]
3. Set STACK[TOP]=ITEM. [Insert ITEM in new TOP position.]
4. RETURN.

This procedure deletes the top element of STACK and assigns it to the variable ITEM.

1. [STACK has an item to be removed? Check for empty stack]


If TOP=-1, then: Print: UNDERFLOW/ Stack is empty, and Return.
2. Set ITEM=STACK[TOP]. [Assign TOP element to ITEM.]
3. Set TOP=TOP-1. [Decrease TOP by 1.]
4. Return.

Program:

Input
#include <iostream>
using namespace std;

Umair Page 20
#define STACKSIZE 10

int Top=-1;
int Stack[STACKSIZE];
void Push(int);
int Pop(void);
boolIsEmpty(void);
boolIsFull(void);
void Traverse(void);

int main( )

cout<<" \n";
cout<<" :p Stack :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) UmairBashir :) \n";
cout<<" \n\n";

int item, choice;


while( 1 )

cout<<"\n\n";

cout<< " ******* STACK OPERATIONS ********* \n\n";


cout<< " 1-Push item \n 2-Pop Item \n";
cout<< " 3-Traverse / Display Stack Items \n 4-Exit.";
cout<< " \n\n\t Your choice ---> ";

cin>> choice;
switch(choice)

case 1: if(IsFull())cout<< "\n Stack Full/Overflow\n";


else

cout<< "\n Enter a number: "; cin>>item;


Push(item); }
break;

Umair Page 21
case 2: if(IsEmpty())cout<< "\n Stack is empty) \n";
else
{

item=Pop();
cout<< "\n deleted from Stack = "<<item<<endl;}
break;

case 3: if(IsEmpty())cout<< "\n Stack is empty) \n";


else

cout<< "\n List of Item pushed on Stack:\n";


Traverse();

break;

case 4: exit(0);
default:

cout<< "\n\n\t Invalid Choice: \n";

} // end of switch block


} // end of while loop
} // end of ofmain() function

void Push(int item)

Stack[++Top] = item;

int Pop( )

return Stack[Top--];

Umair Page 22
boolIsEmpty( )

{
if(Top == -1 )
return true ;

else
return false;

boolIsFull( )

if(Top == STACKSIZE-1 )
return true ;

else
return false;

void Traverse( )

intTopTemp = Top;
do

cout<< Stack[TopTemp--]<<endl;} while(TopTemp>= 0);

Umair Page 23
Output

Umair Page 24
Practical # 8
Queue:
A queue is a linear list of elements in which deletion can take place only at
one end, called the front, and insertions can take place only at the other end, called the rear. The
term front and rear are used in describing a linear list only when it is implemented as a
queue. Queue is also called first-in-first-out (FIFO) lists. Since the first element in a queue will
be the first element out of the queue. In other words, the order in which elements enters a queue
is the order in which they leave.

Algorithm:
Insertion in Queue:
ENQUEUE(QUEUE, MAXSIZE, FRONT, REAR,COUNT, ITEM)
This algorithm inserts an element ITEM into a circular queue.
1. [QUEUE already filled?]
If COUNT = MAXSIZE then: [ COUNT is number of values in the QUEUE]
Write: OVERFLOW, and Return.
2. [Find new value of REAR.]
If COUNT= 0, then: [Queue initially empty.]
Set FRONT= 0 and REAR = 0
Else: if REAR = MAXSIZE - 1, then:
Set REAR = 0
Else:
Set REAR = REAR+1.
[End of If Structure.]
3. Set QUEUE[REAR] = ITEM. [This insert new element.]
4. COUNT=COUNT+1 [ Increment to Counter. ]
5. Return.

Deletion in Queue:
DEQUEUE(QUEUE, MAXSIZE, FRONT, REAR,COUNT, ITEM)
This procedure deletes an element from a queue and assigns it to the
variable ITEM.
1. [QUEUE already empty?]
If COUNT= 0, then: Write: UNDERFLOW, and Return.
2. Set ITEM = QUEUE[FRONT].
3. Set COUNT = COUNT -1
4. [Find new value of FRONT.]

Umair Page 25
If COUNT = 0, then: [There was one element and has been deleted ]
Set FRONT= -1, and REAR = -1.
Else if FRONT= MAXSIZE, then: [Circular, so set Front = 0 ]
Set FRONT = 0
Else:
Set FRONT:=FRONT+1.
[End of If structure.]
5. Return ITEM

Program:

Input
#include<iostream>
using namespace std;
class queue

public:
int q[5],front,rear,x,result;
voidenq();
voiddque();
voiddisp();
queue()

cout<<" \n";
cout<<" :p Queue :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) UmairBashir :) \n";
cout<<" \n\n";

front=0;
rear=0;

}
}

void queue::enq()

if(rear>=5)

Umair Page 26
cout<<"\nQueue overflow!!\n";

else

cout<<"\nEnter the number to be inserted: ";


cin>>x;
rear++;
q[rear]=x;
cout<<"\nNumber pushed in the queue:"<<q[rear];

}
}

void queue::dque()

if(rear==0)
cout<<"\nQueue underflow!!\n";

else

if(front==rear)
{

front=0;
rear=0;

else
front++;

cout<<"\nDeleted element is:";


result=q[front];
cout<<result;

Umair Page 27
void queue::disp()

if(rear==0)
cout<<"\nQueue underflow!!\n";

else

cout<<"\nContents of queue is:";


for(int i=front+1;i<=rear;i++)
cout<<q[i]<<"\t";

int main()

int c;

queuequ;

do

cout<<"\n1.Insertion\n2.Deletion\n3.Display\n";
cout<<"\nEnter your choice:";

cin>>c;
switch(c)

case 1:
qu.enq();
break;

case 2:
qu.dque();
break;

case 3:
qu.disp();

Umair Page 28
break;

default:
cout<<"\nInvalid choice!!\n";

}
}

while(c<4);

Output

Umair Page 29
Practical # 9
Array by Using Pointer:
A pointer is a variable whose value is the address of another variable.
Like any variable or constant, you must declare a pointer before you can work with it. There are
few important operations, which we will do with the pointers very frequently.

(a) we define a pointer variables


(b) assign the address of a variable to a pointer
(c) access the value at the address available in the pointer variable.

This is done by using unary operator * that returns the value of the
variable located at the address specified by its operand. Following example makes use of these
operations:

Algorithm:

Here LA is a Linear array with lower boundary LB and upper boundary UB. This algorithm
traverses LA applying an operation Process to each element of LA. 1. [Initialize counter.] Set
K=LB.
2. Repeat Steps 3 and 4 while KUB.
3. [Visit element.] Apply PROCESS to LA[K].
4. [Increase counter.] Set k=K+1.
[End of Step 2 loop.]
5. Exit.

Program:

Input
#include <iostream>
using namespace std;

Umair Page 30
int main ()

cout<<" \n";
cout<<" :p Array by using Pointer :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) UmairBashir :) \n";
cout<<" \n\n";

int var = 20; // actual variable declaration.


int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";


cout << var << endl; // print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl; // access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;

Output

Umair Page 31
Practical # 10
Bubble Sort by using
pointer:
Bubble sort, sometimes referred to as sinking sort, is a simple sorting
algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items
and swaps them if they are in the wrong order. The pass through the list is repeated until no
swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison
sort, is named for the way smaller elements "bubble" to the top of the list. Although the
algorithm is simple, it is too slow and impractical for most problems even when compared
to insertion sort. It can be practical if the input is usually in sort order but may occasionally have
some out-of-order elements nearly in position.

Algorithm:

Procedure Bubble Sort ( A : list of sortable items )


n = length (A)
repeat
swapped = false
for i = 1 to n-1 inclusive do

/* if this pair is out of order */

if A[i-1] > A[i] then

/* swap them and remember something changed */

swap( A[i-1], A[i] )


swapped = true
end if
end for
until not swapped
end procedure

Umair Page 32
Program:

Input
#include <iostream>
using namespace std;
void bubble(int*,int);

int main()

cout<<" \n";
cout<<" :p Bubble Sorting :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) Umair Bashir :) \n";
cout<<" \n\n";

int Array[5],size=5,*pointer;
int i;

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

cout<<"Enter element no: "<<i+1<<endl;


cin>>Array[i];

pointer=Array;
bubble(pointer,size);

void bubble(int *pointer,int size)

int count1,count2,swap;

for(count1=0;count1<size-1;count1++)

Umair Page 33
for(count2=0;count2<size-count1-1;count2++)

if(*(pointer+count2)>*(pointer+count2+1))

swap=*(pointer+count2);
*(pointer+count2)=*(pointer+count2+1);
*(pointer+count2+1)=swap;

}
}

for(count1=0;count1<size;count1++)

cout<<*(pointer+count1)<<" \n ";

Output

Umair Page 34
Practical # 11

Linear Search by Using


Pointer
Linear search is the simplest search algorithm; it is a special case of brute-force
search. Its worst case cost is proportional to the number of elements in the list; and so is its
expected cost, if all list elements are equally likely to be searched for. Therefore, if the list has
more than a few elements, other methods (such as binary search or hashing) will be faster, but
they also impose additional requirements.

Algorithm:
SUPPOSE AN ARRAY A WITH ELEMENTS INDEXED 1 TO N IS TO BE SEARCHED FOR
A VALUE X. THE FOLLOWING PSEUDOCODE PERFORMS A FORWARD SEARCH, RETURNING N + 1 IF
THE VALUE IS NOT FOUND:

SET I TO 1.
REPEAT THIS LOOP:
IF I > N, THEN EXIT THE LOOP.
IF A[I] = X, THEN EXIT THE LOOP.
SET I TO I + 1.
RETURN I.

THE FOLLOWING PSEUDOCODE SEARCHES THE ARRAY IN THE REVERSE ORDER,


RETURNING 0 WHEN THE ELEMENT IS NOT FOUND:

SET I TO N.
REPEAT THIS LOOP:
IF I 0, THEN EXIT THE LOOP.
IF A[I] = X, THEN EXIT THE LOOP.
SET I TO I 1.
RETURN I.

Umair Page 35
Program:
Input

#include<iostream>
using namespace std;

int main()

int no,sno,i,*j,a[10];

cout<<" \n";
cout<<" :p LINEAR SEARCH :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) Umair Bashir :) \n";
cout<<" \n\n";
cout<<"Enter the range of array # \n";
cin>>no;
cout<<"Enter the elemnts of array # \n";
j=&a[i];

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

cin>>a[i];
cout<<"Enter the number to search # \n";
cin>>sno;

for(i=0;i<no;i++)
if(sno==a[i])

cout<<"The number " <<sno<< "is present at location " <<i;


break;
}
if(sno!=a[i])
{
cout<<"NOT present in array";
}
cout<<"\n************************************************************";
cout<<"\n************************************************************";
cout<<"\n************************************************************";
return 0;
}

Umair Page 36
Output

Umair Page 37
Practical # 12

Binary Search by Using


Pointer
A binary search or half-interval search algorithm finds the position of a specified
input value (the search "key") within an array sorted by key value. For binary search, the array
should be arranged in ascending or descending order. In each step, the algorithm compares the
search key value with the key value of the middle element of the array. If the keys match, then a
matching element has been found and its index, or position, is returned. Otherwise, if the search
key is less than the middle element's key, then the algorithm repeats its action on the sub-array to
the left of the middle element or, if the search key is greater, on the sub-array to the right. If the
remaining array to be searched is empty, then the key cannot be found in the array and a special
"not found" indication is returned.
A binary search halves the number of items to check with each iteration, so
locating an item (or determining its absence) takes logarithmic time. A binary search is
a dichotomic divide and conquer search algorithm.

Algorithm:
int binary_search ( int A[], int key, int imin, int imax)

{
// test if array is empty
if (imax < imin)
// set is empty, so return value showing not found
return KEY_NOT_FOUND;

else

{
// calculate midpoint to cut set in half
int imid = midpoint(imin, imax);

// three-way comparison
if (A[imid] > key)

Umair Page 38
// key is in lower subset
return binary_search(A, key, imin, imid-1);

else if (A[imid] < key)


// key is in upper subset

return binary_search(A, key, imid+1, imax);


else

// key has been found


return imid;

}
}

Program:
Input

#include<iostream>
using namespace std;

int const n=10;


int binarysearch(int*,int);

int main()

cout<<" \n";
cout<<" :p BINARY SEARCH :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) Umair Bashir :) \n";
cout<<" \n\n";

int a[n]={3,5,9,11,15,17,22,25,37,28};
int sky,loc;

cout<<"Enter search key#\n";


cin>>sky;

int *j;
j=&a[0];

Umair Page 39
loc=binarysearch(j,sky);

if(loc==-1)

cout<<"Search key is not in array";


else

cout<<"the serach key"<<sky<<"is at location"<<loc<<endl;

return 0;

int binarysearch(int *a,int sky)

int start=0,end=n-1,mid=int((start+end)/2),loc;
while(start<=end && a[mid]!=sky)

if(sky<a[mid])
end=mid-1;

else
start=mid+1;
mid=int((start+end)/2);

}
{

if(a[mid]==sky)
loc=mid;

else
loc=-1;
return loc;
}
}

Umair Page 40
Output

Umair Page 41
Practical # 16
Structure:
Structures are used to represent a record, suppose you want to keep
track of your books in a library. You might want to track the following attributes about each
book.
To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than one member, for your program. The format of
the struct statement is this:

struct [structure tag]


{
member definition;
member definition;
...
member definition;
} [one or more structure variables];

Program:
Input

#include <iostream>
#include <cstring>

using namespace std;

struct Books

char title[50];
char author[50];
char subject[100];
int book_id;

};

Umair Page 42
int main( )

cout<<" \n";
cout<<" :p Structure :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) Umair Bashir :) \n";
cout<<" \n\n";

struct Books Book1; // Declare Book1 of type Book


struct Books Book2; // Declare Book2 of type Book

// book 1 specification

strcpy( Book1.title, "Learn C++ Programming");


strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification

strcpy( Book2.title, "Telecom Billing");


strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info

cout << "Book 1 title : " << Book1.title <<endl;


cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;

// Print Book2 info

cout << "Book 2 title : " << Book2.title <<endl;


cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;

return 0;

Umair Page 43
Output

Umair Page 44
Practical # 17
Structure to array:
The inventory and the label program examples of the last section
handle only a single record. More realistically, a useful program may need to handle many such
records. As in previous cases where we needed to store a list of items, we can use an array as our
data structure. In this case, the elements of the array are structures of a specified type. For
example:

struct inventory
{
int part_no;
float cost;
float price;
};

struct inventory table[4];

which defines an array with four elements, each of which is of type struct inventory, i.e. each is
an inventory structure.

Program:
Input

#include <iostream>
#include <cstring>

using namespace std;

struct Books

char title[50];
char author[50];
char subject[100];
int book_id;

Umair Page 45
};

int main( )

cout<<" \n";
cout<<" :p Structure to Array :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) Umair Bashir :) \n";
cout<<" \n\n";

struct Books Book1; // Declare Book1 of type Book


struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Data Structure");
strcpy( Book1.author, "Baqer Main");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Computer Organizaition");
strcpy( Book2.author, "Usman Humaiyu");
strcpy( Book2.subject, "Architecture");
Book2.book_id = 6495700;

// Print Book1 info


cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;

// Print Book2 info


cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;

return 0;

Umair Page 46
Output

Umair Page 47
Practical # 18
Structure to Pointer:
Passing and returning structures to functions may not be efficient,
particularly if the structure is large. We can eliminate this excessive data movement by passing
pointers to the structures to the function, and access them indirectly through the pointers.

Program:
Input

#include <iostream>
#include <cstring>

using namespace std;

void printBook( struct Books *book );

struct Books

char title[50];
char author[50];
char subject[100];
int book_id;

};

int main( )

cout<<" \n";
cout<<" :p Structure to Pointer :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) Umair Bashir :) \n";
cout<<" \n\n";

Umair Page 48
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// Book 1 specification

strcpy( Book1.title, "Learn C++ Programming");


strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// Book 2 specification

strcpy( Book2.title, "Telecom Billing");


strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info, passing address of structure


printBook( &Book1 );

// Print Book1 info, passing address of structure


printBook( &Book2 );

return 0;

// This function accept pointer to structure as parameter.


void printBook( struct Books *book )

cout << "Book title : " << book->title <<endl;


cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;

Umair Page 49
Output

Umair Page 50
Practical # 19
Structure to Function:
This makes it possible to pass functions as arguments to other
functions. This capability, although not often used, is extremely useful when it is appropriate.
For example, as we initially defined the collections, even though we were careful to design our
collection so that it would handle any type of data, we limited ourselves to collections of only
one type of data in any one program. This is caused by the need to define an external function for
comparing items. Ideally, we would like to specify a general comparison function function for
the objects in the collection when we constructed the collection. In C, this is easy (although the
syntax is definitely non-intuitive!).

Program:
Input

#include <iostream>
#include <cstring>

using namespace std;

void printBook( struct Books book );

struct Books

{
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( )

cout<<" \n";
cout<<" :p Structure to Function :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) Umair Bashir :) \n";

Umair Page 51
cout<<" \n\n";

struct Books Book1; // Declare Book1 of type Book


struct Books Book2; // Declare Book2 of type Book

// book 1 specification

strcpy( Book1.title, "Learn C++ Programming");


strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification

strcpy( Book2.title, "Telecom Billing");


strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info


printBook( Book1 );

// Print Book2 info


printBook( Book2 );

return 0;
}

void printBook( struct Books book )

cout << "Book title : " << book.title <<endl;


cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;

Umair Page 52
Output

Umair Page 53
Practical # 20
Link-list:
A linked list is a data structure consisting of a group
of nodes which together represent a sequence. Under the simplest form, each node is composed
of a data and a reference (in other words, a link) to the next node in the sequence; more complex
variants add additional links. This structure allows for efficient insertion or removal of elements
from any position in the sequence.

Program:
Input

#include <iostream>
using namespace std;

struct Node

int data;
Node* next;

};

// only for the 1st Node


void initNode(struct Node *head,int n)

cout<<" \n";
cout<<" :p Link-List :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) Umair Bashir :) \n";
cout<<" \n\n";

head->data = n;
head->next =NULL;

Umair Page 54
// apending
void addNode(struct Node *head, int n)

Node *newNode = new Node;


newNode->data = n;
newNode->next = NULL;

Node *cur = head;


while(cur)

if(cur->next == NULL) {
cur->next = newNode;
return;

cur = cur->next;

}
}

void insertFront(struct Node **head, int n)

Node *newNode = new Node;


newNode->data = n;
newNode->next = *head;
*head = newNode;

struct Node *searchNode(struct Node *head, int n)

Node *cur = head;


while(cur)

{
if(cur->data == n) return cur;
cur = cur->next;

Umair Page 55
}

cout << "No Node " << n << " in list.\n";

bool deleteNode(struct Node **head, Node *ptrDel) {


Node *cur = *head;
if(ptrDel == *head)

*head = cur->next;
delete ptrDel;
return true;

while(cur)

if(cur->next == ptrDel)

cur->next = ptrDel->next;
delete ptrDel;
return true;

cur = cur->next;

return false;

/* reverse the list */


struct Node* reverse(struct Node** head)

Umair Page 56
Node *parent = *head;
Node *me = parent->next;
Node *child = me->next;

/* make parent as tail */


parent->next = NULL;

while(child)

me->next = parent;
parent = me;
me = child;
child = child->next;

me->next = parent;
*head = me;
return *head;

/* Creating a copy of a linked list */


void copyLinkedList(struct Node *node, struct Node **pNew)

if(node != NULL) {
*pNew = new Node;
(*pNew)->data = node->data;
(*pNew)->next = NULL;
copyLinkedList(node->next, &((*pNew)->next));
}
}

/* Compare two linked list */


/* return value: same(1), different(0) */
int compareLinkedList(struct Node *node1, struct Node *node2)

static int flag;

/* both lists are NULL */

Umair Page 57
if(node1 == NULL && node2 == NULL)

flag = 1;

else

if(node1 == NULL || node2 == NULL)


flag = 0;
else if(node1->data != node2->data)
flag = 0;
else
compareLinkedList(node1->next, node2->next);

return flag;

void deleteLinkedList(struct Node **node)

struct Node *tmpNode;


while(*node)

tmpNode = *node;
*node = tmpNode->next;
delete tmpNode;

}
}

void display(struct Node *head)

Node *list = head;

Umair Page 58
while(list)

cout << list->data << " ";


list = list->next;

cout << endl;


cout << endl;

int main()

struct Node *newHead;


struct Node *head = new Node;
initNode(head,10);
display(head);

addNode(head,20);
display(head);

addNode(head,30);
display(head);

addNode(head,35);
display(head);

addNode(head,40);
display(head);

insertFront(&head,5);
display(head);

int numDel = 5;
Node *ptrDelete = searchNode(head,numDel);
if(deleteNode(&head,ptrDelete))
cout << "Node "<< numDel << " deleted!\n";
display(head);

cout << "The list is reversed\n";


reverse(&head);

Umair Page 59
display(head);

cout << "The list is copied\n";


copyLinkedList(head,&newHead);

display(newHead);

cout << "Comparing the two lists...\n";


cout << "Are the two lists same?\n";

if(compareLinkedList(head,newHead))
cout << "Yes, they are same!\n";

else
cout << "No, they are different!\n";
cout << endl;

numDel = 35;
ptrDelete = searchNode(newHead,numDel);

if(deleteNode(&newHead,ptrDelete))

cout << "Node "<< numDel << " deleted!\n";


cout << "The new list after the delete is\n";
display(newHead);

cout << "Comparing the two lists again...\n";


cout << "Are the two lists same?\n";

if(compareLinkedList(head,newHead))
cout << "Yes, they are same!\n";

else
cout << "No, they are different!\n";

cout << endl;


cout << "Deleting the copied list\n";

deleteLinkedList(&newHead);
display(newHead);
return 0;
}

Umair Page 60
Output

Umair Page 61
Practical # 21
Dynamic memory
Allocation:
The task of fulfilling an allocation request consists of locating a block
of unused memory of sufficient size. Memory requests are satisfied by allocating portions from a
large pool of memory called the heap or free store. At any given time, some parts of the heap
are in use, while some are "free" (unused) and thus available for future allocations.
Several issues complicate the implementation, such as external
fragmentation, which arises when there are many small gaps between allocated memory blocks,
which invalidates their use for an allocation request. The allocator's metadata can also inflate the
size of (individually) small allocations. This is managed often by chunking. The memory
management system must track outstanding allocations to ensure that they do not overlap and
that no memory is ever "lost" as a memory leak.

Program:
Input

#include <iostream>
using namespace std;

int main ()

cout<<" \n";
cout<<" :p dynamic memory allocation :p \n";
cout<<" PROGRAM BY \n";
cout<<" :) Umair Bashir :) \n";
cout<<" \n\n";

double* pvalue = NULL;


pvalue = new double;

*pvalue = 29494.99;

Umair Page 62
cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue;
return 0;

Output

Umair Page 63

You might also like