Com 124 Notes Final
Com 124 Notes Final
Declaration of the Arrays: Any array declaration contains: the array name, the element type and
the array size.
Examples:
int a[20], b[3],c[7];
float f[5], c[2];
char m[4], n[20];
Initialization of an array is the process of assigning initial values. Typically declaration and
initialization are combined.
Examples:
float, b[3]={2.0, 5.5, 3.14};
char name[4]= {‘E’,’m’,’r’,’e’};
int c[10]={0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
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. There are two popular searching techniques/mechanisms:
Linear search and binary search and will be discussed later.
a) Traversing in Linear Array:
It means processing or visiting each element in the array exactly once;
Let ‘A’ is an array stored in the computer’s 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 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 K≤UB.
3. [Visit element.] Apply PROCESS to LA[K].
4. [Increase counter.] Set k=K+1.
[End of Step 2 loop.]
This program will traverse each element of the array to calculate the sum and then
calculate & print the average of the following array of integers. ( 4, 3, 7, -1, 7, 2, 0, 4, 2, 13)
#include <iostream>
using namespace std;
#define size 10 // another way int const size = 10
int main()
{ int x[10]={4,3,7,10,7,2,0,4,2,13}, i, sum=0,LB=0, UB=size;
float av;
for(i=LB;i<UB;i++); sum = sum + x[i];
av = sum/size;
cout << "The sum of the numbers=" <<sum<<endl;
cout << "The average of the numbers=" <<av<<endl;
return 0;
}
/* This program sorts the array elements in the ascending order using
bubble sort method */
#include <iostream>
using namespace std;
int const SIZE = 6;
int main()
{
int a[SIZE]= {77,42,35,12,101,6};
int i;
cout << "The elements of the array before sorting\n";
for (i=0; i<= SIZE-1; i++)
COM 124 – Data Structures & Algorithm Page 4
{cout<< a[i]<<", ";
}
return 0;
}
Home Work
Write a program to determine the median of the array given below:
(9, 4, 5, 1, 7, 78, 22, 15, 96, 45, 25)
Note that the median of an array is the middle element of a sorted array.
#include <iostream>
using namespace std;
int const N=10;
int BinarySearch(int [ ], int); // Function Prototyping
int main()
{
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); // Function call
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;
}
int BinarySearch (int A[], int skey)
{
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;
The Computational Complexity of the Binary Search algorithm is measured by the maximum
(worst case) number of Comparisons it performs for searching operations. The searched array is
divided by 2 for each comparison/iteration.
Therefore, the maximum number of comparisons is measured by:
log2(n) where n is the size of the array
Example:
If a given sorted array 1024 elements, then the maximum number of comparisons required is:
log2(1024) = 10 (only 10 comparisons are enough)
STACKS:
It is an ordered group of homogeneous items of elements. Elements are added to and removed
from the top of the stack (the most recently added items are at the top of the stack). The last
element to be added is the first to be removed (LIFO: Last In, First Out).
Basic operations:
These are two basic operations associated with stack:
Push () is the term used to insert/add an element into a stack.
Pop () is the term used to delete/remove an element from a stack.
Other names for stacks are piles and push-down lists.
Push Operation
Push an item onto the top of the stack (insert an item)
Pop Operation
Pop an item off the top of the stack (delete an item)
Deletion in Queue:
Algorithm: 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
LINKED LIST:
A linked list or one way list is a linear collection of data elements, called
nodes, where the linear order is given by means of “pointers”. Each node is
divided into two parts.
The first part contains the information of the element.
The second part called the link field contains the address of the next node in
the list.
Algorithm: (Traversing a Linked List) Let LIST be a linked list in memory. This algorithm
traverses LIST, applying an operation PROCESS to each element of list. The variable PTR point
to the node currently being processed.
1. Set PTR=HEAD. [Initializes pointer PTR.]
2. Repeat Steps 3 and 4 while PTR!=NULL.
3. Apply PROCESS to PTR-> INFO.
4. Set PTR= PTR-> NEXT [PTR now points to the next node.]
[End of Step 2 loop.]
5. Exit.
b) Searching a Linked List:
Let list be a linked list in the memory and a specific ITEM of information is given to search. If
ITEM is actually a key value and we are searching through a LIST for the record containing
COM 124 – Data Structures & Algorithm Page 14
ITEM, then ITEM can appear only once in the LIST. Search for wanted ITEM in List can be
performed by traversing the list using a pointer variable PTR and comparing ITEM with the
contents PTR->INFO of each node, one by one of list.
Algorithm: SEARCH(INFO, NEXT, HEAD, ITEM, PREV, CURR, SCAN) LIST is a linked list
in the memory. This algorithm finds the location LOC of the node where ITEM first appear in
LIST, otherwise sets LOC=NULL.
1. Set PTR=HEAD.
2. Repeat Step 3 and 4 while PTR≠NULL:
3. if ITEM = PTR->INFO then:
Set LOC=PTR, and return. [Search is successful.]
[End of If structure.]
4. Set PTR=PTR->NEXT
[End of Step 2 loop.]
5. Set LOC=NULL, and return. [Search is unsuccessful.]
6. Exit.
Search Linked List for insertion and deletion of Nodes:
Both insertion and deletion operations need searching the linked list.
To add a new node, we must identify the logical predecessor (address of previous node)
where the new node is to be inserting.
To delete a node, we must identify the location (addresses) of the node to be deleted
and its logical predecessor (previous node).
TREE:
So far, we have been studying mainly linear types of data structures: arrays, lists, stacks and
queues. Now we defines a nonlinear data structure called Tree. This structure is mainly used to
represent data containing a hierarchical relationship between nodes/elements e.g. family trees and
tables of contents.
There are two main types of tree:
General Tree
Binary Tree
General Tree:
A tree where a node can has any number of children / descendants is called
General Tree. For example:
If T1 is nonempty, then its node is called the left successor of R; similarly, if T2 is nonempty,
then its node is called the right successor of R. The nodes with no successors are called the
terminal nodes. If N is a node in T with left successor S1 and right successor S2, then N is called
the parent (or father) of S1 and S2. Analogously, S1 is called the left child (or son) of N, and S2
is called the right child (or son) of N. Furthermore, S1 and S2 are said to siblings (or brothers).
Every node in the binary tree T, except the root, has a unique parent, called the predecessor of N.
The line drawn from a node N of T to a successor is called an edge, and a sequence of
consecutive edges is called a path. A terminal node is called a leaves, and a path ending in a
leaves is called a branch. The depth (or height) of a tree T is the maximum number of nodes in
a branch of T. This turns out to be 1 more than the largest level number of T.
Level of node & its generation:
Each node in binary tree T is assigned a level number, as follows. The root R of the tree T is
assigned the level number 0, and every other node is assigned a level number which is 1 more
than the level number of its parent. Furthermore, those nodes with the same level number are said
to belong to the same generation.
Preorder (N L R):
COM 124 – Data Structures & Algorithm Page 17
a) Process the node/root. (A B D F I C G H J L K)
b) Traverse the Left sub tree.
c) Traverse the Right sub tree.
Inorder (L N R):
a) Traverse the Left sub tree. ( D B I F A G C L J H K )
b) Process the node/root.
c) Traverse the Right sub tree.
Postorder (L R N):
a) Traverse the Left sub tree. ( D I F B G L J K H C A )
b) Traverse the Right sub tree.
c) Process the node/root.