0% found this document useful (0 votes)
21 views

Data structure unit 2 notes

The document provides an overview of arrays, defining them as linear data structures that store collections of similar data types in contiguous memory locations. It covers array properties, declaration, initialization, operations (traversal, insertion, deletion, search, update), and types (one-dimensional, two-dimensional, multi-dimensional). Additionally, it discusses the advantages and disadvantages of arrays, their representation in memory, and various searching techniques including linear and binary search.

Uploaded by

vinaygdev6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Data structure unit 2 notes

The document provides an overview of arrays, defining them as linear data structures that store collections of similar data types in contiguous memory locations. It covers array properties, declaration, initialization, operations (traversal, insertion, deletion, search, update), and types (one-dimensional, two-dimensional, multi-dimensional). Additionally, it discusses the advantages and disadvantages of arrays, their representation in memory, and various searching techniques including linear and binary search.

Uploaded by

vinaygdev6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Data Structure Unit-2

ARRAYS

ARRAYS: “Arrays are defined as the collection of similar types of data items stored at
contiguous memory locations”.
(OR)
An array is a linear data structure. An array is an ordered collection of homogeneous data
element of same data type.
Properties of an array:
➢ Each element in an array is one of the same data type and carries the same size that is 4
bytes.
➢ Elements in array are stored at contiguous memory locations from which the first element
is stored at the smallest memory locations.

Declaration or representation of an array:


Syntax: array_type var_name [array_size]
Ex: int age [10];

Initialization of an array:
Syntax: data_type var_name [array_size]={argument list};
Ex: int age [10] = {35, 33, 42, 10, 14, 19, 27, 44, 26, 31}

Data type name size elements


❖ Index start with 0.
❖ The arrays length is 10. Which means we can store 10 elements.
❖ Each element in the array can be accessed via its index.

Operations on arrays:
1) Traversal: This operation is used to print the elements of the array.
2) Insertion: It is used to add an element at a particular index.
3) Deletion: It is used to delete an element from a particular index.
4) Search: It is used to search an element using the given index.
5) Update: It updates an element at a particular index.

Types of arrays:
1) One dimensional array
2) Two-dimensional array
3) Multi-dimensional array

1.One dimensional array: A variable which represents the list of items using only one index is
called one dimensional array.
(or)It is containing one subscript value is called one dimensional array.
Syntax: type array_name [size];
Ex: int group [10]; Here int is a data type, group is a variable name, 10 is the size of array, and
index starts from 0 to 9.

1
Ex: int A [6];
Address 100 102 104 106 108 110
A

0 1 2 3 4 5
How can you find the element? A [4] = 93;
Add A [i] = base address (l0) +I * size of data type (w)
Add A [4] =100 + 4* 2
=108
2.Two dimensional arrays:
A variable which represents the list of items using two indexes is called two dimensional arrays.
(or)
It is containing two subscript value is called one dimensional array. In 2-D array the data is
stored in rows and columns format.
Syntax: type array_name [row_size] [column_size] = {list of values};
Ex: int table [2] [3] = {0, 0, 0, 1, 1, 1};
Here the elements of first row initializes to zero and the elements of second row initializes to
one.
Int table [2] [3] = {{0, 0, 0}, {1, 1, 1}}
In 2-D array the row_size can be omitted.

3.multi-dimensional array: A variable which represents the list of items using more than two
indexes is called multi-dimensional array.
(or)
It is containing one or more subscript value is called one dimensional array.
Syntax: type array_name [S1] [S2] [S3];
Where as type is data type, S1 is a block size, S2 is row size, S3 is column size.

Advantages for array:


• It is used to represent multiple data items of same type by using single name.
• It can be used to implement other data structures like linked lists, stacks, queues, tree
graphs etc.
• Two dimensional arrays are used to represent matrices.
• Many databases include one dimensional array whose elements are records.

Disadvantage for array:


• We must know in advance the how many elements are to be stored in array.
• Array is static structure. It means that array is of fixed size. The memory which is
allocated to array cannot be increased or decreased.
• The elements of array are stored in consecutive memory locations. So, insertion and
deletion are very difficult and time consuming.

Arrays as abstract data types (ADT):


Arrays are defined as abstract data types because they are capable of holding contiguous
elements in the same order and they permit.

2
Advantages (ADT):
• Fast, random access of elements or items.
• Very more efficient.
Disadvantages (ADT):
• Slow insertion and deletion of elements.

Representation of linear array in memory:


Linear array is a list of finite umber of homogenous data element such that
a) The element of the array is stored in successive memory locations.
b) The elements of the array are referenced by an index set consisting of consecutive or
continues number.
(or)
The element of linear array is stored in consecutive memory location. It is show below.
Linear Array (LA) =
10 20 5 1 100 Values
A[0] A[1] A[2] A[3] A[4] Index start 0 or 1
A[1] A[2] A[3] A[4] A[5] Index start 1 or 0
1000 1002 1004 1006 1008 Address of the memory
Ex: Find the length of array in linear

LA[5]= 10 20 5 1 100
A[0] A[1] A[2] A[3] A[4]
LB (Lower Bound) UB (Upper Bound)

Formula for Length= (UB-LB) +1


= (4-0) +1 = 5 (Length of array is 5)
Ex: Find the location for given Linear array
LA[5]= 1000 1002 1004 1006 1008
10 20 5 1 100
A[1] A[2] A[3] A[4] A[5]
LB (Lower Bound) or Base address UB (Upper Bound)

Formula for Location (Loc(LA[K])= Base(LA)+W(K-LB)


Where as LA is a Linear array, Loc is a location, Base is nothing but a 1st element in memory or
number of words per memory cell for the array, K is a find the Location of the element.
Loc(LA[K]= Base(LA)+W(K-LB)
Loc(LA[5])= 1000+2(5-1) = 1008 (i.e address of 5th location is 1008).

Traversing Linear array:Accessing and processing each element of array exactly once.
Ex: A[5]= 10 20 5 1 100
A[0] A[1] A[2] A[3] A[4]
LB (Lower Bound) UB (Upper Bound)
Here, this program is traverse A and apply operation process to each element of A (A is a array).

3
Program for Traversing
#include <stdio.h> Output:
int main() { enter the size of the array
int a[10],n,i; 2
printf("enter the size of the array \n"); enter the element of the array
scanf("%d",&n); 1
printf("enter the element of the array \n"); 2
for(i=0;i<n;i++) Element in the array to be printed
scanf("%d",&a[i]); a[0]=1
printf("Element in the array to be printed \n"); a[1]=2
for(i=0;i<n;i++)
printf("a[%d]=%d \n",i,a[i]);
getch();
}

Inserting element in linear array: It is used to add a new element in the given collection of
data item.
Ex:
Program for Insertion
#include <stdio.h>
void main()
{
int a[10],i, n, ele, pos;
printf("Enter the number of elements in the array \n");
scanf("%d",&n);
printf("Enter the elements \n");
for (i = 0; i< n;i++)
scanf("%d",&a[i]);
printf("Input array elements are: \n");
for (i = 0; i< n;i++) Output:
printf("a[%d]=%d \n",i,a[i]); Enter the number of elements in the
printf("\nEnter the new element to be inserted: "); array
scanf("%d", &ele); 2
printf("Enter the position where element is to be inserted: "); Enter the elements
scanf("%d",&pos); 1
n=n+1; 2
for(i = n-1; i >= pos; i--) Input array elements are:
a[i+1]=a[i]; a[0]=1
a[pos]=ele; a[1]=2
printf("Element is to be inserted in location is: "); Enter the new element to be inserted:
for (i = 0; i < n; i++) 0
printf("%d ", a[i]); Enter the position where element is to
getch(); be inserted: 0
} Element is to be inserted in location
is: 0 1 2

4
Deleting element in linear array:It is used to deleting an existing element from the given
collection of data items.
Ex:

Program for deletion


#include <stdio.h> Output:
int main( ){ Enter the size of the array: 3
int i, n,pos,a[10]; Enter the elements of the array:
printf("Enter the size of the array: "); a[0] = 1
scanf("%d", &n); a[1] = 2
printf("Enter the elements of the array: \n"); a[2] = 3
for (i = 0; i < n; i++) Enter the index or position of the element to be
{ deleted: 2
printf("a[%d] = ", i); The array after deleting the element is: 1 2
scanf("%d",&a[i]);
}
printf("Enter the index or position of the element to be deleted: ");
scanf("%d", &pos);
if (pos >= n+1)
{
printf (" \n Deletion is not possible in the array.");
}
else
{
for (i = pos; i < n - 1; i++)
a[i] = a[i + 1];
printf("The array after deleting the element is: ");
for (i = 0; i < n - 1; i++)
printf("%d ", a[i]);
}
getch(); }
Searching
Searching: Finding the given key element from large amount of data is called searching.
Ex: Searching the telephone number from the telephone directory
➢ Searching refers to determining whether an element is present in a given list of elements
or not. If the element is found to be in the list, then the search is considered as a
successful search otherwise it will be considered as unsuccessful search.
➢ The search operation returns the location or address of the element found.
➢ Based on the efficiencies with which search is to be made different searching
techniques are 1. Linear/Sequential search, 2. Binary search, 3. Index sequential search
4. Search on ordered table, 5. Interpolation search

5
1.Sequential or Linear search:
➢ Linear search is also known as sequential or continuous search.
➢ Linear search is a process that checks every element in the list sequentially until the
desired element is found.
➢ Linear search is applicable to a table of organized either as an array or linked lists.
➢ Let us assume that ‘a’ is an array of ‘n’ elements. If the key element is search element.
The search starts by sequentially comparing the element of the array one after the other
from beginning to the end. With the element to be searched.
➢ If the key element is found then the location will be displayed otherwise the message
unsuccessful search or key element not found will be displayed.
Ex: key = 40
A [4] = 10 20 30 40

40
By Comparing 40 with each element
1.compare 40 with 10(40==10) condition become false by using relation operator.
2.compare 40 with 20(40==20) condition become false.
3.compare 40 with 30(40==30) condition become false.
4.compare 40 with 40(40==40) condition become True then the element will find.

Program for Linear Search


#include <stdio.h>
int main() {
int n,a[100],key,i,loc=0;
printf("\n Enter the size of array\n");
scanf("%d",&n);
printf("\n Enter array elements \n");
for(i=0;i<n;i++) Output:
scanf("%d",&a[i]); Enter the size of array
printf("\n Enter key element\n"); 3
scanf("%d",&key); Enter array elements
for(i=0;i<n;i++){ 10
if(key==a[i]) 20
{ 30
loc=1; Enter key element
break; 20
} Key element 20 is found at the Location = 2
}
if(loc==1)
printf("Key element %d is found at the Location = %d ",a[i],loc=i+1);
else
printf("Key element is not found");
getch();
}

6
2.Binary search:
➢ Binary search is also known as half interval search.
➢ Binary search is an efficient sorting technique using Divide and Conquer techniques.
That finds the position of key element with in a sorted array.
➢ In binary search all the elements first arranged in ascending order or descending order in
an array.
➢ Binary search method can be done in two ways
1. Iterative method 2.Recursive method

0 1 2 3 4 5 6
10 20 30 40 50 60 70

Low (1st half) Mid (2nd half) High

Mid = (low+high)/2
= (0+6)/2
=3
➢ If the key element is first compared with the middle element in the array. If it is found
then the search is successful and returns the middle position.
➢ Otherwise check the key element is lesser or greater the middle element.
➢ If the key element is lesser than the middle element then the process is repeated again for
the first half of the array.
➢ If the key element is greater than the middle element then the process is repeated again
for the second half of the array.
➢ If the key element is not found then it will display unsuccessful search.

Ex: searching a key element using binary search. Key=60

A[7]= {10, 20, 30, 40, 50, 60, 70, 80} key=60,loc=0,low=0,high=n-1(7-1=6)
0 1 2 3 4 5 6
10 20 30 40 50 60 70

Low (1st half) mid (2nd half) high


Tracing
1.While(low<=high) (0<=6)true
2.Mid= (low +high)/2
= (0+6)/2
=3 ( mid=3)
3.If (key==a[mid]) (60==a[3]) if (60==40) False
Return mid (if the condition is true, mid is update otherwise remain same)
4.Else If (key<a[mid]) (60<a[3]) else if (20>40) False
high=mid-1 (if the condition is true, high is update otherwise remain same)

7
5.Else (key>a[mid]) (60>a[3]) else (20<40) True
Low=mid+1 (if the condition is true, low is update otherwise remain same)
6.Search start from 1st part
0 1 2 3 4 5 6
10 20 30 40 50 60 70

Low mid high


Key=60,low=4,high=6
7.While(low<=high) (4<=6) True
8.Mid= (low +high)/2
= (4+6)/2
=5 (mid=5)
9.If (key==a[mid]) (60==a[5]) if (60==60) True
Return mid (mid=1) then loc=1 is came searching is successful otherwise loc=0 searching
unsuccessful.

Program in Iterative Method


#include <stdio.h>
int main() {
int n,a[10],key,i,mid,high,low,loc;
printf("\n enter the size of array \n");
scanf("%d",&n);
printf("\n enter array elements \n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n enter key element\n");
Output:
scanf("%d",&key);
enter the size of array
loc=0;
3
low=0;
Enter array elements
high=n-1;
10
while(low<=high)
20
{
30
mid=(low+high)/2;
Enter key element
if(key==a[mid])
20
{
Key element 20 is found at the Location = 2
loc=1;
break;
}
else if(key<a[mid])
high=mid-1;
else
low=mid+1;
}
if(loc==1)
printf("key element %d is found at the Location = %d ",key,mid);
8
else
printf("key element is not found");
getch();
}

Program in Recursive
#include <stdio.h>
int b_search(int a[],int,int); loc=1;
int main() { break;
int n,a[10],key,i,loc; }
printf("\n enter the number of element \n"); else if(key<a[mid])
scanf("%d",&n); high=mid-1;
printf("\n enter array elements \n"); else
for(i=1;i<=n;i++) low=mid+1;
scanf("%d",&a[i]); }
printf("\n enter key element\n"); if(loc==1)
scanf("%d",&key); printf("key element %d is found at the
loc=b_search(a,n,key); Location = %d ",key,mid);
getch(); else
} printf("key element is not found");
int b_search(int a[],int n,int key) getch();
{ }
int loc=0,low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
Difference between Linear and Binary Search:

Linear search Binary search


Searching start from one by one from 1st Searching start from middle element of the array.
element to nth element.
Linear search is useful for simple array. Binary search is useful is for larger array.
In linear search array can be sorted or In binary search array is sorted.
unsorted.
It cannot work under divide and conquers It can work under divide and conquers technique.
technique.
Access is very slow Access is faster
Array element is accessed sequentiallyOne must have direct access to the middle
element in the sub list
This can be used in single and multi- This can be used only in single dimensional
dimensional array array

9
Sorting
Sorting: Arranging the data element either in ascending or descending order or alphabetic order.
Types of Sorting Techniques:
1.Selection sort 2.Bubble sort 3.Insertion sort 4.Quick sort 5.Merge sort

1.Selection sort:
Selection sort is very simple to understand and the implement. The name of selection say that
such assuming the current element is the smallest until we find an element smaller than and then
interchange the element. The algorithm however is not efficient for the large array.
EX: 22 44 33 11 1
step 1: Find the smallest element in the list and swap with the first position element into smallest
element. (1 is smallest and swap 22) then we get 1 44 33 11 22.
step 2: Find the 2nd element among the remaining element in the list and swap with the 2nd
position element. (11 is smallest and swap 44) then we get 1 11 33 44 22.
step 3: Find the 3rd element among the remaining element in the list and swap with the 3rd
position element. (22 is smallest and swap 33) then we get 1 11 22 44 33.
step 4: Find the 4th element among the remaining element in the list and swap with the 4th
position element. (33 is smallest and swap 44) then we get 1 11 22 44 33. Or repeat the process
for all the position one after the other from beginning to the end up to n-1 passes.
Here is sorted list is 1 11 22 44 33.
Output:
Program for selection: Enter size of array
#include <stdio.h> 4
int main() { Enter array elements
int a[100],n,i,j,swap; 2
printf(" Enter size of array\n"); 1
scanf("%d",&n); 5
printf("Enter array elements \n"); 3
for(i=0;i<n;i++) Selection sorted array is
scanf("%d",&a[i]); 1 2 3 5
for(i=0;i<n;i++)
{
int min=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[min])
{
min=j;
}
}
if(min!=i)
{ printf("Selection sorted array is \n");
swap=a[i]; for(i=0;i<n;i++)
a[i]=a[min]; printf("%d \n",a[i]);
a[min]=swap; getch();
}} }

10
2.Bubble sort:
It is the most popular sorting technique because it is very simple to understand and simple to
implement at each pass. The array as n element take n - 1 passes to sort the array then number of
passing is equal to n – 1.
Bubble sort is a sorting algorithm that start from the first element of an array and compares it
with the second element then they are swapped. The process repeated for the next two elements.
The entire process is repeated for n elements from one pass. During the next part the same are
the repeated from the beginning of the array to n - 1 element. The last pass ensure that first two
elements of the array are placed in the correct array and finally we get the sorted array.
Ex: 50 40 30 20 10

Pass1: 50 40 30 20 10 Pass2: 40 30 20 10 50 Pass3: 30 20 10 40 50

40 50 30 20 10 30 40 20 10 50 20 30 10 40 50

40 30 50 20 10 30 20 40 10 50 pass 3: 20 10 30 40 50

40 30 20 50 10 Pass 2: 30 20 10 40 50 pass 4: 20 10 30 40 50

Pass 1: 40 30 20 10 50 pass 4: 10 20 30 40 50

Therefore, sorted is 10 20 30 40 50

Program for Bubble sort:


#include <stdio.h>
int main() {
int a[100],n,i,j,swap;
printf(" Enter size of array\n");
scanf("%d",&n);
printf("Enter array elements \n"); Output:
for(i=0;i<n;i++) Enter size of array
scanf("%d",&a[i]); 4
for(i=0;i<n-1;i++) Enter array elements
{ 50
for(j=0;j<n-i-1;j++) 40
{ 30
if(a[j]>a[j+1]) 20
{ bubble sorted array is
swap=a[j]; 20
a[j]=a[j+1]; 30
a[j+1]=swap; 40
}}} 50
printf("bubble sorted array is \n");
for(i=0;i<n;i++)
printf("%d \n",a[i]);
getch();
}
11
3.Insertion sort:
Insertion sort is a sorting algorithm that place the input element and it is suitable place in each
pass by comparing.
(Or)
In insertion sort the first element of the array is assume to be in the correct position next element
is considered as the key element and compare with the element before the key element and its
inserted in its correct position.
Ex: play card we game.
Step1: We have to compare 2nd element with the previous 1st element, if the second element is
smaller than previous element then moves 1st element in one position to right side and insert the
2nd element in the first 1st Position. suppose the 2nd element is large one, then we don’t perform
operation then the value remains at same position.
Step 2: We have to compare 3rd element with the previous 2nd element, if the 3rd element is
smaller than first two elements then we have to move first and second element one position to
the right side and insert the 3rd element in the 1st position. suppose 3rd element is larger than the
previous two element then don’t perform operation then the value remains at same position or
value remains has its, otherwise if the 3rd element is smaller than 2nd element and then 3rd is
larger than 1st element then we have to move 2nd element to one position to right side and 3rd
element is move one position to left side.
Step 3: likewise, we have to continue the process or repeat the process for all the position one
after the other from beginning to the end up to n - 1 passes and we get the sorted list.
Ex: 50 40 30 20 10
Pass1: 50<40 30 20 10 Pass3: 30 40 50<20 10 pass4: 20 30 40 50<10
Pass1: 40 50 30 20 10 30 40<20 50 10 20 30 40<10 50
Pass2: 40 50<30 20 10 30<20 40 50 10 20 30<10 40 50
40 <30 50 20 10 pass3: 20 30 40 50 10 20<10 30 40 50
Pass2: 30 40 50 20 10 Pass4:10 20 30 40 50(element is sorted)

Program for insertion sort Output:


#include <stdio.h> Enter size of array
int main() { 4
int a[100],n,i,j,swap; Enter array elements
printf(" Enter size of array\n"); 25
scanf("%d",&n); 20
printf("Enter array elements \n"); 10
for(i=0;i<n;i++)
15
scanf("%d",&a[i]);
Insertion sorted array is
for(i=1;i<n;i++)
{ 10 15 20 25
for(j=i;j>=1;j--)
{ }
if(a[j]<a[j-1]) }}
{ printf("Insertion sorted array is \n");
swap=a[j]; for(i=0;i<n;i++)
a[j]=a[j-1]; printf("%d \t",a[i]);
a[j-1]=swap; getch();
}
12
Quick sort
It is a one of the best techniques for sorting large set of the element this technique works on the
method of partition based on the divide and Conquer technique.
• Divide and conquer technique nothing but is complete array is divides into a sub arrays, sub
array nothing but a partition of array.
• Partition of array that also known as backbone of quicksort.
• partition of array became two parts:
• 1st part of partition array all elements is less than Pivot element would be left side of the
pivot element.
• 2nd parts of the partition array all elements are greater than the pivot element would be right
side of the pivot element.
• And if element is equal to pivot element that go either way left and right depends on how
you are implement that logic.
• In quick sort we assume that the first element has the pivot element and the variable ‘i’ is
placed next to the pivot element and the variable ‘j’ is placed at the last element of the
unsorted list.
• Quick sort fallows the simple 3 steps.
Step1: while (i<p)
i++;
Compare the i th element is less than pivot(p) element, if it is true then increment by 1.
Repeat the step 1until the condition become false.
Step2: (j>=p)
j---
compare the j th element is greater than or equal to pivot element, if it is true then the
decrement j by 1. Repeat the step2 until the condition become false.
Step3: if(i<j)
Swap(a[i] and a[j])
Else Swap(a[j] and pivot)
If i<j then swap a[i] and a[j] otherwise swap a[j] and pivot element.
EX:54,26,93,17,31,44,55,20 (in that left mark i and right mark is j,pivot=54)

13
Program for quick sort
#include <stdio.h>
int quicksort(int a[],int,int);
int main() Output:
{ Enter size of array
int a[50],n,i; 5
printf(" Enter size of array\n"); Enter array elements
scanf("%d",&n); 25
printf("Enter array elements \n"); 15
for(i=0;i<n;i++) 10
scanf("%d",&a[i]); 5
quicksort(a,0,n-1); 20
printf("quick sorted array is \n"); quick sorted array is
for(i=0;i<n;i++) 5 10 15 20 25
printf("%d \t",a[i]);
getch();
}
int quicksort(int a[],int low,int high)
{
int pivot,swap,i,j;
if(low<high)
{
pivot=low,i=low,j=high;
while(i<j)
{
while(a[i]<=a[pivot]&&i<high)
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
swap=a[i];
a[i]=a[j];
a[j]=swap;
}
}
swap=a[pivot];
a[pivot]=a[j];
a[j]=swap;
quicksort(a,low,j-1);
quicksort(a,j+1,high);
}
}

14
Merge sort:
Merge sort techniques follows the divide and conquer method to solve the list of n elements. The
given array elements are divided into two subarray and each subarray recursively divided into
smaller subarray until each array as a single element or individual element. After getting the
individual components we sorted each subset and combining. And then finally we combine all
the subset of a get a solution for the entire array.
Merge sort can be perform using the following steps.
Step 1: Dividing the array into 2 subarrays until we get individual component.
Step2: Recursively sort the left part of the element.
Step 3: Recursively sort the right part of element.
Step 4: Merge each sorted list into left and right part element into single sorted array.

Ex: 12,8,9,3,11,5,4

Program for mergesort:


#include <stdio.h>
int mergesort(int a[],int,int);
Output:
int merge(int a[],int,int,int);
Enter size of array
int main()
4
{
Enter array elements
int a[50],n,i;
20
printf(" Enter size of array\n");
50
scanf("%d",&n);
30
printf("Enter array elements \n");
10
for(i=0;i<n;i++)
merge sorted array element is
scanf("%d",&a[i]);
10 20 30 50
mergesort(a,0,n-1);
printf("merge sorted array element is \n");
for(i=0;i<n;i++)
printf("%d \t",a[i]);
getch();
}
int mergesort(int a[],int lb,int ub)
{
int mid;
if (lb <ub)

15
{
mid=(lb+ub)/2;
mergesort(a, lb, mid);
mergesort(a, mid+1, ub);
merge(a, lb, mid, ub);
}
}
int merge(int a [], int lb, int mid, int ub)
{
int temp[50],i=lb, j=mid+1, k=lb;
while (i<=mid && j<=ub)
{
if(a[i]<=a[j])
temp[k++] =a[i++];
else
temp[k++] =a[j++];
}
if(i>mid)
{
while(j<=ub)
temp[k++] =a[j++];
}
else
{
while(i<=mid)
temp[k++] =a[i++];
}
for (k=lb;k<=ub;k++)
a[k]=temp[k];
}
Multidimensional arrays and Representation of multidimensional arrays
A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in
tabular form. Data in multidimensional arrays is generally stored in row-major order in the
memory.
The general form of declaring N-dimensional arrays is shown below.
Syntax:
data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array.
array_name: Name of the array.
size1, size2,…, sizeN: Size of each dimension.
Examples:
Two dimensional array: int two_d[10][20];
Three dimensional array: int three_d[10][20][30];

Size of Multidimensional Arrays: The total number of elements that can be stored in a
multidimensional array can be calculated by multiplying the size of all the dimensions.

16
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
To get the size of the array in bytes, we multiply the size of a single element with the total
number of elements in the array.
For example:
Size of array int x[10][20] = 10 * 20 * 4 = 800 bytes. (where int = 4 bytes)
Similarly, size of int x[5][10][20] = 5 * 10 * 20 * 4 = 4000 bytes. (where int = 4 bytes)

The most commonly used forms of the multidimensional array are:


1.Two Dimensional Array 2.Three Dimensional Array

1.Two-Dimensional Array:A two-dimensional array or 2D array in C is the simplest form


of the multidimensional array. We can visualize a two-dimensional array as an array of one-
dimensional arrays arranged one over another forming a table with ‘x’ rows and ‘y’ columns
where the row number ranges from 0 to (x-1) and the column number ranges from 0 to (y-1).

Graphical Representation of Two-Dimensional Array of Size 3 x 3


Declaration of Two-Dimensional Array in C
The basic form of declaring a 2D array with x rows and y columns in C is shown below.
Syntax:data_type array_name[x][y];
were,
data_type: Type of data to be stored in each element.
array_name: name of the array
x: Number of rows.
y: Number of columns.
We can declare a two-dimensional integer array say ‘x’ with 10 rows and 20 columns as:
Example: int x[10][20];

Three-Dimensional Array: A Three-Dimensional Array or 3D array in C is a collection of


two-dimensional arrays. It can be visualized as multiple 2D arrays stacked on top of each
other. Graphical Representation of Three-Dimensional Array of Size 3 x 3 x 3

17
Declaration of Three-Dimensional Array in C
We can declare a 3D array with x 2D arrays each having y rows and z columns using the
syntax shown below.
Syntax: data_type array_name[x][y][z];
data_type: Type of data to be stored in each element.
array_name: name of the array
x: Number of 2D arrays.
y: Number of rows in each 2D array.
z: Number of columns in each 2D array.
Example:
int array[3][3][3];

Initialization of Three-Dimensional Array


Initialization in a 3D array is the same as that of 2D arrays. The difference is as the number of
dimensions increases so the number of nested braces will also increase.
A 3D array in C can be initialized by using:
1.Initializer List 2. Loops

1.Initialization of 3D Array using Initializer List


Method 1:
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23};
Method 2(Better):
int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
Initialization of 3D Array using Loops
It is also similar to that of 2D array with one more nested loop for accessing one more
dimension.
int x[2][3][4];
for (int i=0; i<2; i++) {
for (int j=0; j<3; j++) {
for (int k=0; k<4; k++) { Output:
x[i][j][k] = (some_value); Element at x[0][0][0] = 0
}}} Element at x[0][0][1] = 1
C program to print 3-Dimensional Array Element at x[0][1][0] = 2
#include <stdio.h> Element at x[0][1][1] = 3
int main(void) Element at x[0][2][0] = 4
{ Element at x[0][2][1] = 5
// initializing the 3-dimensional array Element at x[1][0][0] = 6
int x[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4, 5 } }, Element at x[1][0][1] = 7
{ { 6, 7 }, { 8, 9 }, { 10, 11 } } }; Element at x[1][1][0] = 8
// output each element's value Element at x[1][1][1] = 9
for (int i = 0; i < 2; ++i) { Element at x[1][2][0] = 10
for (int j = 0; j < 3; ++j) { Element at x[1][2][1] = 11

18
for (int k = 0; k < 2; ++k) {
printf("Element at x[%i][%i][%i] = %d\n", i,
j, k, x[i][j][k]);
}}}
return (0);
}
Sparse matrices:
A matrix is a two-dimensional data object made of m rows and n columns, therefore having
total m x n values. If most of the elements of the matrix have 0 value, then it is called a sparse
matrix.
Or
Sparse Matrices are those matrices which have the majority of the elements equal to zero.
Example:
00304
00570
00000
02600

Why to use Sparse Matrix instead of simple matrix?


Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to
store only those elements.
Computing time: Computing time can be saved by logically designing a data structure
traversing only non-zero elements.

• Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in


the matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero
elements, we only store non-zero elements. This means storing non-zero elements
with triples- (Row, Column, value).

Sparse Matrix Representations can be done in many ways following are two common
representations:
1. Array representation 2. Linked list representation

Using Arrays Representations:


2D array is used to represent a sparse matrix in which there are three rows named as
Row: Index of row, where non-zero element is located
Column: Index of column, where non-zero element is located
Value: Value of the non zero element located at index – (row, column)

************

19
Assignment Questions
1.What is array? Explain types of arrays with (syntax, Example, declaration).
2.What is Arrays as abstract data types (ADT)?
3. Find the length(A[4]) and location(A[5]) of array in linear for given array (24,5,6,7,20).
4.what Traversing linear arrays and write programs?
5.what Inserting linear arrays and write programs?
6.what Deleting linear arrays and write programs?
7.what is a sorting? Explain types of sorting techniques with program.
8.what is a searching? Explain Linear searching techniques with program.
9.what is a binary search and write a program in recursive.
10. Difference between Linear and binary search.
11. Explain is a Multidimensional array with program?
12.what is Sparse matrix? Write the array representation of sparse matrix.

20

You might also like