You are on page 1of 32

Basics of Data Structures And Arrays

CHAPTER-1
In order to represent and store data in main memory and/or secondary memory, we need
an appropriate model. The different models used to organize data in the main memory
are collectively referred to as data structures, where as the different models used to
organize data in the secondary memory are collectively referred to as file structures.
 Data: The term data simple refers to a value or a set of values. Eg: marks
obtained bya student in an examination etc.
 Data item: A data item refers to a single unit of values. For Example: Rollno,
Name, Address.
 Group Item: Data item that can be divided into sub items are called group
items. Eg:Address.
 Elementary item: Data item that cannot be divided into sub items. For eg:
Marks, Rollno, pincode.
 Entity: An entity is something that has certain attributes or properties.
 Information: Information is a processed data.

DATA TYPE
A data type is a collection of values and set of operations that act on those values.
a) Primitive Data Type: It is a data type that is predefined. The predefined
data type is also known as built-in data type.
For Eg : For C & C++
1) Integers ( int, long) ( 2bytes, 4 bytes)
2) Real ( float, double) ( 4bytes, 8 Bytes)
3) Character (char) ( 1 Byte).

b) User Defined Data Type: A user defined data type is one that user defines
as perhis/her own requirements.
Struct student
{
int rollno;
char name [10];
char address [10]
Dr. Deepti Malhotra Page 1
Basics of Data Structures And Arrays

};

Struct student s1;


Here s1 is declared as a variable of struct student data type.

c) Abstract Data Type:


An abstract data type is a data type that is organized in such a way that the
specification of the values and the specification of the operations on those values
are separated from the representation of the values and the implementation of
operations.

We all know that, by default, all primitive data types (int, float, etc.) support
basic operations such as addition and subtraction. The system provides the
implementations for the primitive data types.

For user-defined data types we also need to define operations. The


implementation for these operations can be done when we want to actually use
them. That means, in general, user defined data types are defined along with
their operations.

To simplify the process of solving problems, we combine the data structures


with their operations and we call this Abstract Data Types (ADTs). An ADT
consists of two parts: 1. Declaration of data 2. Declaration of operations
Commonly used ADTs include: Linked Lists, Stacks, Queues, Priority Queues,
Binary Trees, Dictionaries, Disjoint Sets (Union and Find), Hash Tables, Graphs,
and many others. For example, stack uses LIFO (Last-In-First-Out) mechanism
while storing the data in data structures. The last element inserted into the stack
is the first element that gets deleted. Common operations of it are: creating the
stack, pushing an element onto the stack, popping an element from stack, finding
the current top of the stack, finding number of elements in the stack, etc. While
defining the ADTs do not worry about the implementation details. They come
into the picture only when we want to use them. Different kinds of ADTs are
suited to different kinds of applications, and some are highly specialized to
specific tasks.

Dr. Deepti Malhotra Page 2


Basics of Data Structures And Arrays

DESCRIPTION OF VARIOUS DATA STRUCTURES

The various data structures are divided into following categories


Linear Data Structures: A Data Structure whose elements form a sequence, and every
element in the structure has a unique predecessor and unique successor. Examples of Linear
Data structures are arrays, linked lists, stacks and queues.
Non-Linear Data Structures: A Data Structure whose elements do not form a
sequence, there is no unique predecessor and unique successor. Examples of Linear Data
structures are trees and graphs
ARRAYS
An array is a list of finite number of elements of same data type.
int A [10]
 Here int specifies the type of variable, just as it does with ordinary variables.
 A specifies the name of the variable.
 The [10] tells how many elements of the type int will be in our array.

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.

The individual element of the array is accessed by an index or indices to the array.
Depending on the number of indices required to access an individual element of
an array.

Dr. Deepti Malhotra Page 3


Basics of Data Structures And Arrays

Arrays can be classified as:

One-Dimensional Array/ Linear Array: That requires only one index to access an
individual; element of the array.
Two- Dimensional Array: That requires two indices to access an individual
element ofthe array.
Multi- Dimensional Array: which need 2 or more indices.

STACK
 A stack is a list of elements in which element may be inserted or deleted only at
one end, called the TOP of the STACK.
 Elements are removed from a stack in the reverse order of that in which they were
inserted into the stack.
 Stack is also called as LIFO.

Figure: Stack with 5 Elements


Basic Operations
PUSH : Given a stack S, and an item to be inserted i then the operation push can be
written as Push (s, i)
POP:
i = pop(s) Remove the top element and assign its value to i

QUEUES
 Queue is a linear list in which elements can be inserted only at one end called rear
of the queue and deleted only at the other end called front of the queue.
 Queue of people waiting at counter or a queue of cars etc.
 It is called as FIFO First-in-First-Out.

Dr. Deepti Malhotra Page 4


Basics of Data Structures And Arrays

queue.
Basic Operations
When an element is inserted in a queue, the concept is called EnQueue, and when an element is
removed from the queue, the concept is called DeQueue.

A B C D E F

FRONT REAR

LINKED LIST
 Linked List can be defined as collection of objects called nodes that are randomly
stored in the memory.
 A node contains two fields i.e. data stored at that particular address and the pointer
 which contains the address of the next node in the memory.
 The last node of the list contains pointer to the null.

Linear Linked List

Circular linked list


A circular linked list is a sequence of elements in which every element has a link to its
next element in the sequence and the last element has a link to the first element.

Dr. Deepti Malhotra Page 5


Basics of Data Structures And Arrays

Doubly Linked List

Doubly Linked List is a variation of Linked list in which navigation is possible in both
ways, either forward or backward easily as compared to Single Linked List.
Two “start pointers” – first element and last element
• Each node has a forward pointer and a backward pointer
• Allows traversals both forwards and backwards

Circular Doubly Linked List

Dr. Deepti Malhotra Page 6


Basics of Data Structures And Arrays

TREES

 A tree is s a non-linear data structure that represents a hierarchical relationship


between various elements.
 A binary tree is s a tree that can have utmost two children.

HEAPS
Heap is a binary tree that satisfy the following property:
• Shape property
• Order property

Shape property states that heap is complete or nearly complete binary tree.

Order property states that:


1. Either the element at any node is smallest of all of its children, called min heap
2. Element at any node is largest of all of its children, called max heap.

GRAPHS

A graph G is a ordered set (V,E), where V represent the set of elements , called nodes or
vertices in graph terminology, and E represents the edges between these elements.

Dr. Deepti Malhotra Page 7


Basics of Data Structures And Arrays

LINEAR ARRAY
Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type. Instead
of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is
accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds
to the first element and the highest address to the last element.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant
greater than zero and type can be any valid C data type. For example, to declare a 10-
element array called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as
follows − double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index
Dr. Deepti Malhotra Page 8
Basics of Data Structures And Arrays

of the element within square brackets after the name of the array. For example −
double salary = balance[9];

 Size of the Linear


Array n= ub – lb +1
ub= largest dex
lb = Smallest index

Dr. Deepti Malhotra Page 9


Basics of Data Structures And Arrays

Example: If lb=1

ub=6

n = 6-1+1
n= 6
Example: If lb=0,
ub=6

n = 6-0+1
n=7

3 5 7 8 9
a[0] a[1] a[2] a[3] a[4]
upward downward

The number n is called the size of the Linear Array.

Elements of the Linear Array are denoted as:


𝒂[𝟎], 𝒂[𝟏], 𝒂[𝟐] … … … … . 𝒂[𝒏 − 𝟏] [ 𝑰𝒏 𝑪, 𝑪 + +]
𝒂[𝟏] , 𝒂[𝟐], … … … … … … … … … . . 𝒂[𝒏] [ 𝑰𝒏 𝑷𝒂𝒔𝒄𝒂𝒍]
𝒂[𝒌] Subscripted Variable

Subscript
 Representing Linear Arrays in Memory
1. Let a be a linear Array with n elements. Arrays are stored in consecutive
memory locations.
2. The address of the first element is also known as the base address of the
array denoted by base (a).
𝒍𝒐𝒄 ( 𝒂[𝒌]) = 𝒃𝒂𝒔𝒆 (𝒂) + 𝒘 ( 𝒌 − 𝒍𝒃)
Where w = no of bytes per storage location for one element of the
array. Example int a [10] Base address = 1197
Find the address of the Loc a[3]?
Dr. Deepti Malhotra Page
10
Basics of Data Structures And Arrays

1197 a[0]
1198
1199 a[1]
1200
1201 a[2]
1202
1203 a[3]
1204
1205 a[4]
1206
1207 a[5]
1208
1209 a[6]
1210
1211 a[7]
1212
1213 a[8]
1214

Loc a [3] = 1197 + 2(3-0)


= 1203

1. Find the address of the Loc a[11]? Base address=1197 , w=2

2. Find the address of the Loc a[3] ? , base address =1197 , w=4

Dr. Deepti Malhotra Page


11
Basics of Data Structures And Arrays

Operations on array
a) Traversing: means to visit all the elements of the array in an operation is called
traversing.
b) Insertion: means to put values into an array.

c) Deletion / Remove: to delete a value from an array.


d) Sorting: Re-arrangement of values in an array in a specific order (Ascending or

Descending) is called sorting.


e) Searching: The process of finding the location of a particular element in an

array is called searching. Eg Linear Search and Binary Search.


3 5 12 17 20
a[0] a[1] a[2] a[3] a[4 ]

/*Sum of N Natural Numbers*/


#include <stdio.h>
void main()
{
int i, sum=0;
int a[5]; /*Array Declaration*/
for(i=0;i<=5;i++)
{
printf("Enter number");
scanf("%d",&a[i]); /*Store data in array*/
}
for(i=0;i<=5;i++)
{
sum=sum+a[i]; /*Read data from an array*/
}
printf("\nSum of n Natural NOs=%d",sum);
}

/*Program to find Average marks obtained by a class of 40 students */


Main()
{
Float avg, sum=0;
Int i,;
Int marks[40];
For(i=0;i<=40;i++)
{
Printf(“\n Enter marks”);
Scanf(“%d”, & marks[i]); /*store data in array*/
}
For( i=0;i<=40;i++)

Dr. Deepti Malhotra Page


12
Basics of Data Structures And Arrays

sum=sum +marks[i]; /*read data from an array*/


Avg=Sum/40;
Printf(“\nAverage marks=%f”,avg);
}

/*Program to Find the Largest and Smallest number in an array*/


#include<stdio.h>
int main()
{
int i,arr[10]={2,5,4,1,8,9,11,6,3,7};
int small, large;
small=large =arr[0];
for(i=0;i<10;i++)
{
if ( arr[i] <small)
small=arr[i];
if (arr[i]>large)
large=arr[i];
}
printf("Smallest=%d,Largest=%d\n",small,large);
}

/*Program to Reverse the Elements of an array*/


#include<stdio.h>
int main ()
{
int i,j,temp,arr[10]={2,5,4,1,8,9,11,6,3,7};
for (i=0, j=9; i<j;i++,j--)
{
temp=arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
printf("After reversing the array is: ");
for (i=0; i<10; i++)
printf("\n%d”, arr[i]);
}

After reversing the array is:

7
3
6
11
9
8
1
Dr. Deepti Malhotra Page
13
Basics of Data Structures And Arrays

4
5
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,
 at the end,
 any given index of array.
We can insert the elements wherever we want, which means we can insert either at starting
position or at the middle or at last or anywhere in the array.
Insertion at the Beginning of an Array
When the insertion happens at the beginning, it causes all the existing data items to shift one
step downward. Here, we design and implement an algorithm to insert an element at the
beginning of an array.

Algorithm
We assume A is an array with N elements. The maximum numbers of elements it can store
is defined by MAX. We shall first check if an array has any empty space to store any
element and then we proceed with the insertion process.

Example
Let A be a Linear Array (unordered) with n elements .Here Loc is the first location and
item is the value to be inserted

1 4 7 8 9 13
A[0] A[1] A[2] A[3] A[4] A[5]

InsertatBeginning(A,n,loc,item)
1. Start
2. Set i=n
3. while (i>= loc)
4. Start Loop
5. Set A[i+1] = A[i]
6. Set i= i-1
7. End Loop
7. Set A[Loc] = ITEM
9. Stop

Dr. Deepti Malhotra Page


14
Basics of Data Structures And Arrays

/* WAP for Insertion at the Beginning of an Array*/


#include<stdio.h>
int main()
{
int student[40],loc=0,i,size,value;
printf("enter no of elements in array of students:");
scanf("%d",&size);
printf("enter %d elements are:",size);
for(i=0;i<size;i++)
scanf("%d",&student[i]);
printf("enter the value into that position:");
scanf("%d",&value);
i=size;
while(i>=loc)
{
student[i+1]=student[i];
i=i-1;
}
student[loc]=value;
printf("final array after inserting the value");
for(i=0;i<=size;i++)
printf("%d ",student[i]);
return 0;
}
After inserting the element in the array, the positions or index location is increased but it
does not mean the size of the array is increasing.
The logic used to insert element is −
 Enter the size of the array
 Enter the position where you want to insert the element
 Next enter the number that you want to insert in that position

Insertion at the specified Position


Algorithm
Example
Let A be a Linear Array (unordered) with n elements and Loc<=n. Following algorithm
insert an item into the locth position in array A.

1 4 7 8 9 13
A[0] A[1] A[2] A[3] A[4] A[5]

Dr. Deepti Malhotra Page


15
Basics of Data Structures And Arrays

InsertatLoc(A,n,loc,item)

1. Start
2. Set i=n-1
3. while (i>= loc-1)
4. Start Loop
5. Set A[i+1] = A[i]
6. Set i= i-1
7. End Loop
7. Set A[Loc-1] = ITEM
8. n= n+1
9. Stop

DRY RUN
LOC=3 ITEM=5
i=5 i=4 i=3 i=2
5>=2 4>=2 3>=2 2>=2
a[6] = a[5] a[5] = a[4] a[4] = a[3] a[3] = a[2]
a[6] =13 a[5] =9 a[4] =8 a[3] =7
i=4 i=3 i=2 i=1

A[loc-1] = item
A[2] = 5

/*Program to insert the value at the specific position of the array*/


#include<stdio.h>
int main(){
int student[40],pos,i,size,value;
printf("enter no of elements in array of students:");
scanf("%d",&size);
printf("enter %d elements are:
",size);
for(i=0;i<size;i++)
scanf("%d",&student[i]);
printf("enter the position where you want to insert the element:");
scanf("%d",&pos);
printf("enter the value into that position:");
scanf("%d",&value);
for(i=size-1;i>=pos-1;i--)
{

Dr. Deepti Malhotra Page


16
Basics of Data Structures And Arrays

student[i+1]=student[i];
}
student[pos-1]= value;
printf("final array after inserting the value is
");
for(i=0;i<=size;i++)
printf("%d ",student[i]);
return 0;
}

1 4 7 8 9 13 …..10 6 5 11
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

DRY RUN
POS=7 value=3
1 4 7 8 9 13 3 10 6 5 11
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9] A[10]

i= 9 i>=6 i= 8 i>=6 i= 7 i>=6 i= 6 i>=6 i= 5 i>=2


a[10] = a[9] a[9] = a[8] a[8] = a[7] a[7] = a[6] a[10] = a[9]
i=8 i=7 i=6 i=5 i=8

Example
/*Program to insert element at specified position*/–

#include <stdio.h>
int main()
{
int arr[100] = { 0 };
int i, x, pos, n = 10;
for (i = 0; i < 10; i++) /* initial array of size 10*/
arr[i] = i + 1;
for (i = 0; i < n; i++) /*print the original array */
printf("%d ", arr[i]);
printf("\n");
x = 50; // element to be inserted
pos = 5; //*position at which element is to be inserted*/
n++; // increase the size by 1

Dr. Deepti Malhotra Page


17
Basics of Data Structures And Arrays

for (i = n - 1; i >= pos; i--) // shift elements forward


arr[i] = arr [i - 1];
// insert x at pos
arr[pos - 1] = x;
for (i = 0; i < n; i++)
printf("%d ", arr[i]); // print the updated array
printf("\n");
return 0;
}
Output

1 2 3 4 5 6 7 8 9 10
1 2 3 4 50 5 6 7 8 9 10

INSERTION AT THE END

Example
Let A be a Linear Array (unordered) with n elements and Loc<=n. Following algorithm
insert an item into the locth position in array A.

1 4 7 8 9 13
A[0] A[1] A[2] A[3] A[4] A[5]

Insertat End(A,n,loc,item)
1. Start
2. int i
3. i= n-1
4. while((item< a[i] ) && (i>=0))
4. Start Loop
5. Set A[i+1] = A[i]
6. Set i= i-1
7. End Loop
7. Set A[i+1] = ITEM
8. n= n+1
9. Stop

ANALYSIS OF INSERTION OPERATION


 The best possible case occurs when the item is inserted at the last position. In
this case , no element is moved down.
 The worst case occurs when the item is inserted at the first position. In this
case , all the elements ( n in number) are moved down.
 Thus, the complexity of insertion operation is O(n).
Dr. Deepti Malhotra Page
18
Basics of Data Structures And Arrays

DELETION OPERATION

/*Program to Remove the Element from the Array at the specified position*/

#include<stdio.h>

int main(){

int student[40],pos,i,size;

printf("enter no of elements in array of students:");

scanf("%d",&size);

printf("enter %d elements are:",size);

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

scanf("%d",&student[i]);

printf("enter the position where you want to delete the element:");

scanf("%d",&pos);

for (i = pos - 1; i <size -1; i++)

student[i]=student[i+1];

printf("final array after Deleting the value is");

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

printf("%d ",student[i]);

return 0;

}
1 4 7 8 9 13 10 6 5 11
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

DRY RUN
POS=7 size=10
i= 6 i<9 i= 7 i<9 i= 8 i<9
a[6] = a[7] a[7] = a[8] a[8] = a[9]
i=7 i=8 i=9

Dr. Deepti Malhotra Page


19
Basics of Data Structures And Arrays

ANALYSIS OF DELETION OPERATION


 The best possible case occurs when the item is deleted from the last position.
In this case , no element is moved up.
 The worst case occurs when the item is deleted from the first position. In this
case , almost all the elements ( n -1 in number) are moved up.
 Thus, the complexity of deletion operation is O(n).

LINEAR SEARCH
Linear search is a very simple search algorithm. In this type of search, a sequential search is
made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data collection.

3 5 7 8 9
A [0] A [1] A [2] A [3] A [4]
Algorithm Linear Search (Array A, Value x)
Step 1: Set i to 0
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit

/*Linear Search*/
#include<stdio.h>
#define MAX 50
int main ()
{
int i,n,item, arr[MAX],k;
printf("Ënter the number of elements");
{
scanf("%d",&n);
}
for (i=0; i<n;i++)
scanf("%d",&arr[i]);

Dr. Deepti Malhotra Page


20
Basics of Data Structures And Arrays

printf("Ënter the item to be searched");


scanf("%d",&item);

for(k=0;k<n;k++)
{
/*START FOR*/
if(arr[k]==item)
break;
} /*END FOR*/
if(k<n)
{ /*START IF*/
printf("Ëlement found at %d",k );
} /*END IF*/
else
{ /*START ELSE*/
printf("not found in array");
} /*END ELSE*/
return 0;
}

ANALYSIS OF LINEAR SEARCH


Complexity of linear Search Linear search on a list of n elements. In the worst case,
the search must visit every element once. This happens when the value being
searched for is either the last element in the list, or is not in the list. However, on
average, assuming the value searched for is in the list and each list element is equally
likely to be the value searched for, the search visits only n/2 elements. In best case
the array is already sorted i.e. O(1)

Algorithm Worst Case Average Case Best Case


Linear Search O(n) O(n) O(1)

BINARY SEARCH
Binary Search is a searching algorithm for finding an element's position in a sorted array.In
this approach, the element is always searched in the middle of a portion of an array.

Binary search can be implemented only on a sorted list of items. If the elements are not
sorted already, we need to sort them first.

Dr. Deepti Malhotra Page


21
Basics of Data Structures And Arrays

The array in which searching is to be performed is:

3 5 7 8 9

A[0] A[1] A[2] A[3] A[4]


Low High

1. Let x = 5 be the element to be searched.


2. Set two pointers low and high at the lowest and the highest positions respectively.

3. Find the middle element mid of the array ie. arr[(low + high)/2] = arr[2]= 7

4. If x == mid, then return mid.Else, compare the element to be searched with m.

5. If x > mid, compare x with the middle element of the elements on the right side of mid.
This is done by setting low to low = mid + 1.

6. Else, compare x with the middle element of the elements on the left side of mid. This is
done by setting high to high = mid - 1.

7. Repeat steps 3 to 6 until low meets high.

8. x = 5 is found.

9.

ALGORITHM
Binarysearch(a,n,item,loc)
Begin
set beg=0

Dr. Deepti Malhotra Page


22
Basics of Data Structures And Arrays

set end=n-1
Set mid=(beg+end)/2
while((beg<=end) and(a[mid]!=item) do
if(item<a[mid]) then
set end=mid-1
else
set beg=mid+1
endif
set mid=(beg+end)/2
endwhile
if(beg>end) then
set loc=-1
else
set loc=mid
endif
end
/*Program to implement Binary Search*/
#include <stdio.h>
void main( )
{
int arr[10] = { 1, 2, 3, 9, 11, 13, 17, 25, 57, 90 } ;
int mid, lower = 0 , upper = 9, num, flag = 1 ;
printf ( "Enter number to search: " ) ;
scanf ( "%d", &num ) ;
for ( mid = ( lower + upper ) / 2 ;
lower <= upper ;
mid = ( lower + upper ) / 2 )
{
if ( arr[mid] == num )
{
printf ( "The number is at position %d in the array.", mid ) ;
flag = 0 ;
break ;
}
if ( arr[mid] > num )

Dr. Deepti Malhotra Page


23
Basics of Data Structures And Arrays

upper = mid - 1 ;
else
lower = mid + 1 ;
}
if ( flag )
printf ( "Element is not present in the array." ) ;
}

ANALYSIS OF BINARY SEARCH


A binary search halves the number of items to check with each iteration, so
locating an item (or determining its absence) takes logarithmic time. Therefore, for n
elements in the array there will be log2n iterations . This complexity will be same
irrespective of the position of the element, even if it is not present in the array.
Algorithm Worst Case Average Case Best Case
Binary Search O (log2n) O(log2n) O(log2n)

/*Program to Merge Arrays*/


#include <stdio.h>

void merge(int [], int, int [], int, int []);

int main()
{
int a[100], b[100], m, n, c, sorted[200];

printf("Input number of elements in first array\n");


scanf("%d", &m);

printf("Input %d integers\n", m);


for (c = 0; c < m; c++) {
scanf("%d", &a[c]);
}

printf("Input number of elements in second array\n");


scanf("%d", &n);

printf("Input %d integers\n", n);


for (c = 0; c < n; c++) {
scanf("%d", &b[c]);
}
Dr. Deepti Malhotra Page
24
Basics of Data Structures And Arrays

merge(a, m, b, n, sorted);

printf("Sorted array:\n");

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


printf("%d\n", sorted[c]);
}
return 0;
}

void merge(int a[], int m, int b[], int n, int sorted[]) {


int i, j, k;
j = k = 0;

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


if (j < m && k < n) {

if (a[j] < b[k]) {


sorted[i] = a[j];
j++;
}
else {
sorted[i] = b[k];
k++;
}
i++;
}

else if (j == m) {
for (; i < m + n;) {
sorted[i] = b[k];
k++;
i++;
}
}

else {
for (; i < m + n;) {
sorted[i] = a[j];
j++;
i++;
}
}
}
}

Dr. Deepti Malhotra Page


25
Basics of Data Structures And Arrays

Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size [x][y], you would write something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier.
A two-dimensional array can be considered as a table which will have x number of
rows and y number of columns.
 Size of the 2d-Array = m*n
where m = Rows n =
Columns Representing 2d- Array in
Memory
A two-dimensional array a, which contains three rows and four columns can be shown
as follows –
Col 1 Col 2 Col 3 Col 4
Row a[1][1] A a[1] [2] D a[1] [3] G a[1] [4] J
1 a[2] [1] B a[2] [2] E a[2] [3] H a[2] [4] K

Row a[3] [1] C a[3] [2] F a[3] [3] I a[3] [4] L

Row3

Thus, every element in the array a is identified by an element name of the form a[ i ][ j
], where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely
identify each element in 'a'.
A 2D array’s elements are stored in continuous memory locations. It can be
represented in memory using any of the following two ways:

1. Column-Major Order

2. Row-Major Order

Dr. Deepti Malhotra Page


26
Basics of Data Structures And Arrays

1. Column-Major Order: In this method the elements are stored column wise.

Row-Major Order:

In this method the elements are stored


row wise, 3 x 4 array will stored as
below:

Dr. Deepti Malhotra Page


27
Basics of Data Structures And Arrays

Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each
row. Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional. The
following
initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements
An element in a two-dimensional array is accessed by using the subscripts, i.e.,
row indexand column index of the array. For example −
int val = a[2][3];
The above statement will take the 4th element from the 3rd row of the array. You
can verify it in the above figure. Let us check the following program where we have
used a nested loopto handle a two-dimensional array −

Calculate the address of the element in the jth row and kth column .i.e Loc
(a[j] [k])

Column
Major 𝒍𝒐𝒄 𝒂[𝒋][𝒌] = 𝒃𝒂𝒔𝒆 (𝒂) + 𝒘 [𝒎(𝒌 − 𝟏) + (𝒋 − 𝟏)]

Row Major
𝒍𝒐𝒄 𝒂[𝒋][𝒌] = 𝒃𝒂𝒔𝒆 (𝒂) + 𝒘 [𝒏(𝒋 − 𝟏) + (𝒌 − 𝟏)]

Dr. Deepti Malhotra Page


28
ADA CHAPTER-1

Example Given array a [25] [4] , where base address is 200 and
w=4. Calculate a [12] [3]?
m = Rows =25 n = Columns =
4 Row Major
𝒍𝒐𝒄 𝒂[𝒋][𝒌] = 𝒃𝒂𝒔𝒆 (𝒂) + 𝒘 [𝒏(𝒋 − 𝟏) + (𝒌 − 𝟏)]
𝒍𝒐𝒄 𝒂[𝟏𝟐][𝟑] = 𝒃𝒂𝒔𝒆 (𝒂) + 𝒘 [𝒏(𝒋 − 𝟏) + (𝒌 − 𝟏)]
= 200+4 [4(12-1) + (3-1)]

= 200+4 [46] = 384 Ans

Column Major
𝒍𝒐𝒄 𝒂[𝒋][𝒌] = 𝒃𝒂𝒔𝒆 (𝒂) + 𝒘 [𝒎(𝒌 − 𝟏) + (𝒋 − 𝟏)]
= 200+4 [25 (3-1) + (12-1)]
= 200+4 [61] = 444 Ans

Example: Given an array [18, 6] of integers. Calculate address of


element T [4, 6] and T [12, 6] where BA=900 And w=4

Why Constant Time for Accessing Array Elements?


To access an array element, the address of an element is computed as an offset
from the base address of the array and one multiplication is needed to compute
what is supposed to be added to the base address to get the memory address of
the element. First the size of an element of that data type is calculated and then
it is multiplied with the index of the element to get the value to be added to the
base address.
This process takes one multiplication and one addition. Since these two operations
take constant time, we can say the array access can be performed in constant
time.

Dr. Deepti Malhotra Page 10


ADA CHAPTER-1

Advantages of Arrays
• Simple and easy to use
• Faster access to the elements (constant access)

Disadvantages of Arrays
• Preallocates all needed memory up front and wastes memory space for
indices in the array that are empty.
• Fixed size: The size of the array is static (specify the array size before using it).
• One block allocation: To allocate the array itself at the beginning, sometimes
it may not be possible to get the memory for the complete array (if the array size
is big).
• Complex position-based insertion: To insert an element at a given position, we
may need to shift the existing elements. This will create a position for us to
insert the new element at the desired position. If the position at which we
want to add an element is at the beginning, then the shifting operation is more
expensive.

Special Matrices
A square matrix has the same number of rows and columns. Some special forms of
square matrices are:
a) Diagonal Matrix
2
5
7
9

b) Tridiagonal Matrix
2 1
3 5 8
6 7 2
4 9

c) Lower Triangular Matrix

Dr. Deepti Malhotra Page


130
ADA CHAPTER-1

2
3 5
8 6 7
4 1 4 9

d) Upper Triangular Matrix

2 1 8 6
5 3 4
7 2
9
Sparse Matrices
𝟎 𝟐 𝟎 (𝟎
𝟎 𝟑)
𝟎 𝟗 𝟎
Fig1: A 3*3 Sparse Matrix

Array Representation of Sparse Matrices


In array representation, an array of triplets of type
<row , columm , element>
<3,3,3>

Is used to store non- zero element, Where first field of the triplet is used to record
row position, second to record column position, and third one to record the non
zero element of the sparse matrix.

Dr. Deepti Malhotra Page


131
ADA CHAPTER-1

Dr. Deepti Malhotra Page


232

You might also like