0% found this document useful (0 votes)
30 views18 pages

Abstract Data Types (Arrays and Queues)

The document discusses array and queue data structures. It defines an array as a fixed-size container that holds elements of the same type. Arrays allow direct access to elements via indexes and support basic operations like traversal, insertion, deletion, searching and updating. Common applications of arrays include matrices, lookup tables, and contact lists. A queue is similar to a stack but opens at both ends, following a first-in, first-out principle where the oldest entry is served first.

Uploaded by

MOSES ALLEN
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
30 views18 pages

Abstract Data Types (Arrays and Queues)

The document discusses array and queue data structures. It defines an array as a fixed-size container that holds elements of the same type. Arrays allow direct access to elements via indexes and support basic operations like traversal, insertion, deletion, searching and updating. Common applications of arrays include matrices, lookup tables, and contact lists. A queue is similar to a stack but opens at both ends, following a first-in, first-out principle where the oldest entry is served first.

Uploaded by

MOSES ALLEN
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

DATA STRUCTURES AND ALGORITHMS

Abstract Data Types (Arrays and Queues).


ARRAY DATA STRUCTURE
Array is a container which can hold a fix number of items and these items should be of the same type.
Most of the data structures make use of arrays to implement their algorithms. Following are the
important terms to understand the concept of Array.
• Element − Each item stored in an array is called an element.
• Index − Each location of an element in an array has a numerical index, which is used
to identify the element.

Array Representation

Arrays can be declared in various ways in different languages. For illustration, let's take C array
declaration.

Arrays can be declared in various ways in different languages. For illustration, let's take C array
declaration.

As per the above illustration, following are the important points to be considered.
• Index starts with 0.
• Array length is 10 which means it can store 10 elements.
• Each element can be accessed via its index. For example, we can fetch an element at
index 6 as 9.

Basic Operations

Following are the basic operations supported by an array.


• Traverse − print all the array elements one by one.
• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the value.
• Update − Updates an element at the given index.

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 1


• In C, when an array is initialized with size, then it assigns defaults values to its elements in
following order.

Data Type Default Value

bool false

char 0

int 0

float 0.0

double 0.0f

void

wchar_t 0

Traverse Operation

This operation is to traverse through the elements of an array.


Example
Following program traverses and prints the elements of an array:
#include <stdio.h>
main() {
int GEORGE[5] = {1,3,5,7,8};
int i = 0 ,n = 5;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("GEORGE[%d] = %d \n", i, GEORGE[i]);
}
}
OUTPUT

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 2


Insertion Operation

Insert operation is to insert one or more data elements into an array. Based on the requirement, a new
element can be added at the beginning, end, or any given index of array.
Algorithm

Let Array is a linear unordered array of MAX elements.

Example

Result
Let GEORGE be a Linear Array unordered with N elements and K is a positive integer such that
K<=N. Below is the algorithm where ITEM is inserted into the Kth position of GEORGE −
1. Start
2. Set J=N
3. Repeat steps 4 and 5 while J >= K
4. Set GEORGE[J+1] = GEORGE[J]
5. Set J = J-1
6. Set GEORGE[K] = ITEM
7. Reset N = N+1
8. Stop

Example

Below is the implementation of the above algorithm –


#include <stdio.h>
main()
{
int GEORGE[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i<n; i++)
{
printf("GEORGE[%d] = %d \n", i, GEORGE[i]);
}
n = n + 1;
while( j >= k)
{
GEORGE[j+1] = GEORGE[j];
j = j - 1;
}
GEORGE[k] = item;
printf("The array elements after insertion :\n");
for(i = 0; i<n; i++)
{

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 3


printf("GEORGE[%d] = %d \n", i, GEORGE[i]);
}
}

OUTPUT:

Deletion Operation

Deletion refers to removing an existing element from the array and re-organizing all elements of an
array.
Algorithm
Consider GEORGE is a linear array with N elements and K is a positive integer such that K<=N.
Following is the algorithm to delete an element available at the Kth position of GEORGE.
1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set GEORGE[J-1] = GEORGE[J]
5. Set J = J+1
6. Set N = N-1
7. Stop

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 4


Following is the implementation of the above algorithm –

#include <stdio.h>
void main()
{
int GEORGE[] = {1,3,5,7,8};
int k = 3, n = 5;
int i, j;
printf("The original array elements are :\n");
for(i = 0; i<n; i++)
{
printf("GEORGE[%d] = %d \n", i, GEORGE[i]);
}
j = k;
while( j < n)
{
GEORGE[j-1] = GEORGE[j];
j = j + 1;
}
n = n -1;
printf("The array elements after deletion :\n");
for(i = 0; i<n; i++)
{
printf("GEORGE[%d] = %d \n", i, GEORGE[i]);
}
}

OUTPUT

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 5


Search Operation

You can perform a search for an array element based on its value or its index.
Algorithm
Consider GEORGE is a linear array with N elements and K is a positive integer such that K<=N.
Following is the algorithm to find an element with a value of ITEM using sequential search.
1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF GEORGE[J] is equal ITEM THEN GOTO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
7. Stop

Example
Following is the implementation of the above algorithm −
#include <stdio.h>
void main()
{
int GEORGE[] = {1,3,5,7,8};
int item = 5, n = 5;
int i = 0, j = 0;
printf("The original array elements are :\n");
for(i = 0; i<n; i++)
{
printf("GEORGE[%d] = %d \n", i, GEORGE[i]);
}
while( j < n)
{
if( GEORGE[j] == item )
{
break;
}
j = j + 1;
}
printf("Found element %d at position %d\n", item, j+1);
}

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 6


OUTPUT:

Update Operation

Update operation refers to updating an existing element from the array at a given index.
Algorithm
Consider GEORGE is a linear array with N elements and K is a positive integer such that K<=N.
Following is the algorithm to update an element available at the Kth position of GEORGE.
1. Start
2. Set GEORGE[K-1] = ITEM
3. Stop
Example
Following is the implementation of the above algorithm −
#include <stdio.h>
void main()
{
int GEORGE[] = {1,3,5,7,8};
int k = 3, n = 5, item = 10;
int i;
printf("The original array elements are :\n");
for(i = 0; i<n; i++)
{
printf("GEORGE[%d] = %d \n", i, GEORGE[i]);
}
GEORGE[k-1] = item;
printf("The array elements after updation :\n");
for(i = 0; i<n; i++)
{
printf("GEORGE[%d] = %d \n", i, GEORGE[i]);
}
}

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 7


OUTPUT:

Applications of Array Data Structure:


Below are some applications of arrays.
• Arrays are used to implement data structures like a stack, queue, etc.
• Arrays are used for matrices and other mathematical implementations.
• Arrays are used in lookup tables in computers.
• Arrays can be used for CPU scheduling.

Real-Time Applications of Array:


• Contact lists on mobile phones.
• Matrices use arrays which are used in different fields like image processing, computer
graphics, and many more.
• Arrays are used in online ticket booking portals.
• Pages of book.
• IoT applications use arrays as we know that the number of values in an array will
remain constant, and also that the accessing will be faster.
• It is also utilised in speech processing, where each speech signal is represented by an
array.
• The viewing screen of any desktop/laptop is also a multidimensional array of pixels.

Advantages of array data structure:


• Arrays store multiple data of similar types with the same name.
• It allows random access to elements.
• As the array is of fixed size and stored in contiguous memory locations there is no
memory shortage or overflow.
• It is helpful to store any type of data with a fixed size.
• Since the elements in the array are stored at contiguous memory locations it is easy to
iterate in this data structure and unit time is required to access an element if the index
is known.

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 8


Disadvantages of array data structure:
• The size of the array should be known in advance.
• The array is a static data structure with a fixed size so, the size of the array cannot be
modified further and hence no modification can be done during runtime.
• Insertion and deletion operations are costly in arrays as elements are stored in
contiguous memory.
• If the size of the declared array is more than the required size then, it can lead to
memory wastage.

QUEUE DATA STRUCTURE

Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open
at both its ends. One end is always used to insert data (enqueue) and the other is used to
remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item
stored first will be accessed first.

FIFO Principle of Queue:


• A Queue is like a line waiting to purchase tickets, where the first person in line is the
first person served. (i.e. First come first serve).
• Position of the entry in a queue ready to be served, that is, the first entry that will be
removed from the queue, is called the front of the queue(sometimes, head of the
queue), similarly, the position of the last entry in the queue, that is, the one most
recently added, is called the rear (or the tail) of the queue.
Characteristics of Queue:
• Queue can handle multiple data.
• We can access both ends.
• They are fast and flexible.

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 9


Queue Representation:

Like stacks, Queues can also be represented in an array: In this representation, the Queue is
implemented using the array. Variables used in this case are
• Queue: the name of the array storing queue elements.
• Front: the index where the first element is stored in the array representing the queue.
• Rear: the index where the last element is stored in an array representing the queue.

Basic Operations

Queue operations may involve initializing or defining the queue, utilizing it, and then completely
erasing it from the memory. Here we shall try to understand the basic operations associated with
queues −
• enqueue() − add (store) an item to the queue.
• dequeue() − remove (access) an item from the queue.
Few more functions are required to make the above-mentioned queue operation efficient. These are

• peek() − Gets the element at the front of the queue without removing it.
• isfull() − Checks if the queue is full.
• isempty() − Checks if the queue is empty.
In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing (or storing)
data in the queue we take help of rear pointer.
Let's first learn about supportive functions of a queue −
peek()
This function helps to see the data at the front of the queue. The algorithm of peek() function is as
follows −
Algorithm
begin procedure peek
return queue[front]
end procedure
Implementation of peek() function in C programming language −
Example
int peek() {
return queue[front];
}
isfull()
As we are using single dimension array to implement queue, we just check for the rear pointer to reach
at MAXSIZE to determine that the queue is full. In case we maintain the queue in a circular linked-
list, the algorithm will differ. Algorithm of isfull() function −

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 10


Algorithm
begin procedure isfull

if rear equals to MAXSIZE


return true
else
return false
endif

end procedure
Implementation of isfull() function in C programming language −
Example
bool isfull() {
if(rear == MAXSIZE - 1)
return true;
else
return false;
}
isempty()
Algorithm of isempty() function −
Algorithm
begin procedure isempty

if front is less than MIN OR front is greater than rear


return true
else
return false
endif

end procedure
If the value of front is less than MIN or 0, it tells that the queue is not yet initialized, hence empty.
Here's the C programming code −
Example
bool isempty() {
if(front < 0 || front > rear)
return true;
else
return false;
}

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 11


Enqueue Operation

Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively
difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
• Step 1 − Check if the queue is full.
• Step 2 − If the queue is full, produce overflow error and exit.
• Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
• Step 4 − Add data element to the queue location, where the rear is pointing.
• Step 5 − return success.

Sometimes, we also check to see if a queue is initialized or not, to handle any unforeseen situations.
Algorithm for enqueue operation
procedure enqueue(data)

if queue is full
return overflow
endif

rear ← rear + 1
queue[rear] ← data
return true

end procedure

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 12


Algorithm for ENQUEUE operation

1. Check if the queue is full or not.

2. If the queue is full, then print overflow error and exit the program.

3. If the queue is not full, then increment the tail and add the element.

Implementation of enqueue() in C programming language −


Example
int enqueue(int data)
if(isfull())
return 0;

rear = rear + 1;
queue[rear] = data;

return 1;
end procedure

Dequeue Operation

Accessing data from the queue is a process of two tasks − access the data where front is pointing and
remove the data after access. The following steps are taken to perform dequeue operation −
• Step 1 − Check if the queue is empty.
• Step 2 − If the queue is empty, produce underflow error and exit.
• Step 3 − If the queue is not empty, access the data where front is pointing.
• Step 4 − Increment front pointer to point to the next available data element.
• Step 5 − Return success.

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 13


Algorithm for dequeue operation
procedure dequeue

if queue is empty
return underflow
end if

data = queue[front]
front ← front + 1
return true

end procedure

Algorithm for DEQUEUE operation

1. Check if the queue is empty or not.

2. If the queue is empty, then print underflow error and exit the program.

3. If the queue is not empty, then print the element at the head and increment the head.

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 14


Implementation of dequeue() in C programming language −

Example
int dequeue() {
if(isempty())
return 0;

int data = queue[front];


front = front + 1;

return data;
}

Implementation of Queue in C Language:

#include <stdio.h>
#include<stdlib.h>
#define MAX 50
void insert();
void delete();
void display();
int GEORGE[MAX];
int rear = - 1;
int front = - 1;
int main()
{
int choice;
while (1)
{
printf("\n 1.Insert element to queue GEORGE");
printf("\n 2.Delete element from queue GEORGE");
printf("\n 3.Display all elements of queue GEORGE");
printf("\n 4.Quit Queue GEORGE");
printf("\n Enter your choice = : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 15


exit(1);
default:
printf("Wrong choice");
}
}
}

void insert()
{
int item;
if(rear == MAX - 1)
printf("Queue Overflow");
else
{
if(front== - 1)
front = 0;
printf("Insert the element in queue : ");
scanf("%d", &item);
rear = rear + 1;
GEORGE[rear] = item;
}
}
void delete()
{
if(front == - 1 || front > rear)
{
printf("Queue Underflow");
return;
}
else
{
printf("Element deleted from queue is : %d \t", GEORGE[front]);
front = front + 1;
}
}

void display()
{
int i;
if(front == - 1)
printf("Queue is empty");
else
{
printf("Queue is : \t");
for(i = front; i <= rear; i++)
printf("%d ", GEORGE[i]);
}
}

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 16


OUTPUT

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 17


Queue is used when things don’t have to be processed immediately, but have to be processed
in First In First Out order.

Useful Applications of Queue


• When a resource is shared among multiple consumers. Examples include CPU
scheduling, Disk Scheduling.
• When data is transferred asynchronously (data not necessarily received at the same rate
as sent) between two processes. Examples include IO Buffers, pipes, etc.

Applications of Queue in Operating systems:


• Semaphores
• FCFS ( first come first serve) scheduling, example: FIFO queue
• Spooling in printers
• Buffer for devices like keyboard

Applications of Queue in Networks:


• Queues in routers/ switches
• Mail Queues
• Variations: ( Deque, Priority Queue, Doubly Ended Priority Queue )

Some other applications of Queue:


• Applied as waiting lists for a single shared resource like CPU, Disk, and Printer.
• Applied as buffers on MP3 players and portable CD players.
• Applied on Operating system to handle the interruption.
• Applied to add song at the end or to play from the front.
• Applied on WhatsApp when we send messages to our friends and they don’t have an
internet connection then these messages are queued on the server of WhatsApp.

Advantages of Queue:
• A large amount of data can be managed efficiently with ease.
• Operations such as insertion and deletion can be performed with ease as it follows the
first in first out rule.
• Queues are useful when a particular service is used by multiple consumers.
• Queues are fast in speed for data inter-process communication.
• Queues can be used in the implementation of other data structures.

Disadvantages of Queue:
• The operations such as insertion and deletion of elements from the middle are time
consuming.
• Limited Space.
• In a classical queue, a new element can only be inserted when the existing elements are
deleted from the queue.
• Searching an element takes O(N) time.
• Maximum size of a queue must be defined prior.

GEORGE WAINAINA 0718313173/0731919231 georgewainaina58@gmail.com Page 18

You might also like