100% found this document useful (1 vote)
902 views18 pages

Com 124 Notes Final

The document discusses arrays and operations on arrays such as traversing, insertion, deletion, sorting, and searching. It provides examples of declaring and initializing arrays in different programming languages. For sorting, it describes the bubble sort algorithm through multiple passes to reorder array elements in ascending or descending order. It also explains linear and binary search algorithms for finding a specific element in an array, with linear search comparing all elements sequentially while binary search divides the array space by half in each iteration.

Uploaded by

Nafruono Jonah
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
100% found this document useful (1 vote)
902 views18 pages

Com 124 Notes Final

The document discusses arrays and operations on arrays such as traversing, insertion, deletion, sorting, and searching. It provides examples of declaring and initializing arrays in different programming languages. For sorting, it describes the bubble sort algorithm through multiple passes to reorder array elements in ascending or descending order. It also explains linear and binary search algorithms for finding a specific element in an array, with linear search comparing all elements sequentially while binary search divides the array space by half in each iteration.

Uploaded by

Nafruono Jonah
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/ 18

COM 124 – Data Structures & Algorithm Page 1

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

COM 124 – Data Structures & Algorithm Page 2


5. Exit.

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

b) Sorting in Linear Array:


Sorting an array is the ordering the array elements in ascending (increasing - from min to max)
or descending (decreasing – from max to min) order.
Example:
{2 1 5 7 4 3} {1, 2, 3, 4, 5,7} ascending order
{2 1 5 7 4 3} {7,5, 4, 3, 2, 1} descending order
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.

COM 124 – Data Structures & Algorithm Page 3


Bubble Sort
Pass=1 Pass=2 Pass=3 Pass=4

215743 125437 124357 123457

125743 125437 124357 123457

125743 125437 124357 123457


125743 124537 123457
125473 124357
125437

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.

/* 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]<<", ";
}

int pass, hold;


for (pass=1; pass<= SIZE-1; pass++)
{
for (i=0; i<= SIZE-pass; i++)
{
if(a[i] >a[i+1])
{
hold =a[i];
a[i]=a[i+1];
a[i+1]=hold;
}
}
}
cout<< "\n\nThe elements of the array after sorting\n";
for (i=0; i<= SIZE-1; i++)
{
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.

c) Searching in Linear Array:

COM 124 – Data Structures & Algorithm Page 5


The process of finding a particular element of an array is called Searching”. If the item is not
present in the array, then the search is unsuccessful. There are two types of search (Linear
search and Binary Search)
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.
/* This program use linear search in an array to find the LOCATION of the given
Key value */
/* This program is an example of the Linear Search*/
#include <iostream>
using namespace std;
int const N=10;
int LinearSearch(int [ ], int); // Function Prototyping
int main()
{
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";
COM 124 – Data Structures & Algorithm Page 6
else
cout<< " The search key "<<Skey<<" is at location " <<LOC<<endl;
return 0;
}
int LinearSearch (int b[ ], int skey) // function definition
{
int i;
for (i=0; i<= N-1; i++) if(b[i] == skey) return i;
return -1;
}
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. If the search key is less than the middle
element of array, the first half of the array is searched. If the search key is not the middle element
of in the specified sub array, the algorithm is repeated on one quarter of the original array. The
search continues until the sub array consist of one element that is equal to the search key (search
successful). But if Search-key not found in the array then the value of END of new selected range
will be less than the START of new selected range.
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.]

COM 124 – Data Structures & Algorithm Page 7


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

// C++ Code for Binary Search

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

COM 124 – Data Structures & Algorithm Page 8


else
START = MID + 1;
MID=int((START+END)/2);
}
if(A[MID] == skey)
LOC=MID;
else LOC= -1;
return LOC;
}
Computational Complexity of Binary Search

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)

Computational Complexity of Linear Search


Note that the Computational Complexity of the Linear Search is the maximum number of
comparisons you need to search the array. As you are visiting all the array elements in the worst
case, then, the number of comparisons required is: n (n is the size of the array)
Example:
If a given an array of 1024 elements, then the maximum number of comparisons required is: n-1
= 1023 (As many as 1023 comparisons may be required)

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

COM 124 – Data Structures & Algorithm Page 9


A stack is a list of elements in which an element may be inserted or deleted only at one end,
called TOP of the stack. The elements are removed in reverse order of that in which they were
inserted into the stack.

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)

COM 124 – Data Structures & Algorithm Page 10


Algorithm for PUSH:
Algorithm: PUSH(STACK, TOP, STACKSIZE, ITEM)
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.

Algorithm for POP:


Algorithm: POP(STACK, TOP, ITEM)
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.
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.

COM 124 – Data Structures & Algorithm Page 11


There are main two ways to implement a queue:
1. Circular queue using array
2. Linked Structures (Pointers)
Primary queue operations:
Enqueue: insert an element at the rear of the queue
Dequeue: remove an element from the front of the queue
Following is the algorithm which describes the implementation of Queue using an
Array.
Insertion in Queue:
Algorithm: 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:
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

COM 124 – Data Structures & Algorithm Page 12


4. [Find new value of FRONT.]
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

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.

To see this more clearly let’s look at an example:

COM 124 – Data Structures & Algorithm Page 13


The Head is a special pointer variable which contains the address of the first node of the list. If
there is no node available in the list then Head contains NULL value that means, List is empty.
The left part of the each node represents the information part of the node, which may contain an
entire record of data (e.g. ID, name, marks, age etc). the right part represents pointer/link to the
next node. The next pointer of the last node is null pointer signal the end of the list.
Advantages:
List of data can be stored in arrays but linked structures (pointers) provide several advantages.
 A linked list is appropriate when the number of data elements to be represented in data
structure is unpredictable.
 It also appropriate when there are frequently insertions & deletions occurred in the list.
 Linked lists are dynamic, so the length of a list can increase or decrease as necessary.
Operations on Linked List:
There are several operations associated with linked list i.e.

a) Traversing a Linked List


Suppose we want to traverse LIST in order to process each node exactly once.
The traversing algorithm uses a pointer variable PTR which points to the node that is currently
being processed. Accordingly, PTR->NEXT points to the next node to be processed so,
PTR=HEAD [ Moves the pointer to the first node of the list]
PTR=PTR->NEXT [ Moves the pointer to 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:

COM 124 – Data Structures & Algorithm Page 15


Binary Tree:
A tree in which each element may has 0-child, 1-child or maximum of 2-children.
A Binary Tree T is defined as finite set of elements, called nodes, such that:
a) T is empty (called the null tree or empty tree.)
b) T contains a distinguished node R, called the root of T, and the remaining nodes of T form an
ordered pair of disjoint binary trees T1 and T2.
If T does contain a root R, then the two trees T1 and T2 are called, respectively, the left sub tree
and right sub tree of R.

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.

COM 124 – Data Structures & Algorithm Page 16


Complete Binary Tree:
Consider a binary tree T. each node of T can have at most two children.
Accordingly, one can show that level n-2 of T can have at most two nodes.
A tree is said to be complete if all its levels, except possibly the last have the maximum number of
possible nodes, and if all the nodes at the last level appear as far left as possible.
Extended Binary Tree: 2-Tree:
A binary tree T is said to be a 2-tree or an extended binary tree if each node N has either 0 or 2
children. In such a case, the nodes, with 2 children are called internal nodes, and the node with 0
children are called external node.

Traversing of Binary Tree:

A traversal of a tree T is a systematic way of accessing or visiting all the node of T.


There are three standard ways of traversing a binary tree T with root R. these are:

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

COM 124 – Data Structures & Algorithm Page 18

You might also like