Unit Ii-Arrays Array: CM - GFGC Magadi 1
Unit Ii-Arrays Array: CM - GFGC Magadi 1
Unit Ii-Arrays Array: CM - GFGC Magadi 1
Array
An array is a list of a finite number ‘n’ of homogeneous data element such that
a. The elements of the array are reference respectively by an index set
consisting of n consecutive numbers.
b. The element of the array are respectively in successive memory locations.
The number n of elements is called the length or size of the array. The length or the
numbers of elements of the array can be obtained from the index set by the formula
When LB = 0,
Length = UB – LB + 1
When LB = 1,
Length = UB
Where,
UB is the largest index called the Upper Bound
LB is the smallest index, called the Lower Bound
Let LA be a linear array in the memory of the computer. The memory of the
computer is simply a sequence of address location as shown below,
1000
1001
1002
1003
1004
Cm_gfgc magadi 1
Base (LA) and called the base address of LA.
Using the base address of LA, the computer calculates the address of any element of
LA by the formula
Where, w is the number of words per memory cell for the array LA.
ARRAY OPERATIONS
1. Traversing
Let A be a collection of data elements stored in the memory of the computer.
Suppose if the contents of the each elements of array A needs to be printed or to
count the numbers of elements of A with a given property can be accomplished by
Traversing.
Traversing is a accessing and processing each element in the array exactly once.
Hear LA is a linear array with the lower bound LB and upper bound UB. This
algorithm traverses LA applying an operation PROCESS to each element of LA
using while loop.
1. [Initialize Counter] set K:= LB
2. Repeat step 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]
5. Exit
Program
#include<stdio.h>
#include<conio.h>
int main()
{
int A[100],K=0,UB;
printf(“Enter the Array size less than 100: “);
Cm_gfgc magadi 2
scanf(“%d”,&UB);
printf(“Enter the elements in array: \n”);
for(K=0;K<UB;K++)
{
scanf(“%d”,&A[K]);
}
printf(“The Traverse of array is:\n”);
for(K=0;K<UB;K++)
{
printf(“%d\n”,A[K]);
}
getch();
return 0;
}
2. Inserting
Inserting an element at the “end” of the linear array can be easily done provided
the memory space allocated for the array is large enough to accommodate the
additional element.
Inserting an element in the middle of the array, then on average, half of the
elements must be moved downwards to new locations to accommodate the new
element and keep the order of the other elements.
Algorithm:
Here LA is a linear array with N elements and K is a positive integer such that K ≤ N.
This algorithm inserts an element ITEM into the Kt h position in LA.
Cm_gfgc magadi 3
1. [Initialize counter] set J:= N
7. Exit
Program
#include <stdio.h>
int main()
{
int array[100], position, c, n, value;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the location where you wish to insert an element\n");
scanf("%d", &position);
printf("Enter the value to insert\n");
scanf("%d", &value);
for (c = n - 1; c >= position - 1; c--)
array[c+1] = array[c];
array[position-1] = value;
printf("Resultant array is\n");
for (c = 0; c <= n; c++)
printf("%d\n", array[c]);
return 0;
}
Cm_gfgc magadi 4
3. Deleting
Deleting an element at the “end” of the linear array can be easily done with
difficulties.
Algorithm
Here LA is a linear array with N elements and K is a positive integer such that K ≤ N.
this algorithm deletes the Kt h element from LA
2. Repeat for J = K to N – 1
[End of loop]
4. Exit
program
#include <stdio.h>
int main()
{
int array[100], position, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
Cm_gfgc magadi 5
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the location where you wish to delete element\n");
scanf("%d", &position);
if (position >= n+1)
printf("Deletion not possible.\n");
else
{
for (c = position - 1; c < n - 1; c++)
array[c] = array[c+1];
printf("Resultant array:\n");
for (c = 0; c < n - 1; c++)
printf("%d\n", array[c]);
}
return 0;
}
Multidimensional Arrays
Cm_gfgc magadi 6
Size of multidimensional arrays
Total number of elements that can be stored in a multidimensional array can be
calculated by multiplying the size of all the dimensions.
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.
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], c[2][2];
int i, j;
Cm_gfgc magadi 7
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("Enter b%d%d: ", i+1, j+1);
scanf("%f", &b[i][j]);
}
if(j==1)
printf("\n");
}
return 0;
}
Ouput
Cm_gfgc magadi 8
Enter elements of 1st matrix
Enter a11: 2;
Enter a22: 2;
Enter b12: 0;
Sum Of Matrix:
2.2 0.5
-0.9 25.0
Cm_gfgc magadi 9
2. Row-Major Order
1. Column-Major Order:
In this method the elements are stored column wise, i.e. m elements of first column are
stored in first m locations, m elements of second column are stored in next m locations
and so on. E.g.
A 3 x 4 array will stored as below:
2. Row-Major Order:
In this method the elements are stored row wise, i.e. n elements of first row are stored
in first n locations, n elements of second row are stored in next n locations and so on.
E.g.
Cm_gfgc magadi 10
A 3 x 4 array will stored as below:
Cm_gfgc magadi 11
Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as given:
(1) Row Major System (2) Column Major System
Row Major System:
The address of a location in Row Major System is calculated using the following
formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
Column Major System:
The address of a location in Column Major System is calculated using the following
formula:
Address of A [ I ][ J ] Column Major Wise = B + W * [( I – Lr ) + M * ( J – Lc )]
Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
Cm_gfgc magadi 12
M = Number of row of the given matrix
N = Number of column of the given matrix
Introduction to Sorting
Sorting is nothing but arranging the data in ascending or descending order. The
term sorting came into picture, as humans realised the importance of searching
quickly.
There are so many things in our real life that we need to search for, like a particular
record in database, roll numbers in merit list, a particular telephone number in
telephone directory, a particular page in a book etc. All this would have been a mess if
the data was kept unordered and unsorted, but fortunately the concept
of sorting came into existence, making it easier for everyone to arrange data in an
order, hence making it easier to search.
Sorting Efficiency
If you ask me, how will I arrange a deck of shuffled cards in order, I would say, I will
start by checking every card, and making the deck as I move on.
It can take me hours to arrange the deck in order, but that's how I will do it.
Cm_gfgc magadi 13
Since the beginning of the programming age, computer scientists have been working on
solving the problem of sorting by coming up with various different algorithms to sort
data.
The two main criterias to judge which algorithm is better than the other have been:
There are many different techniques available for sorting, differentiated by their
efficiency and space requirements. Following are some sorting techniques which we
will be covering in next few tutorials.
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
Bubble sort
algorithm in which each pair of adjacent elements is compared and the elements are
swapped if they are not in order. This algorithm is not suitable for large data sets as its
average and worst case complexity are of Ο(n2) where n is the number of items.
Cm_gfgc magadi 14
How Bubble Sort Works?
We take an unsorted array for our example. Bubble sort takes Ο(n 2) time so we're
Bubble sort starts with very first two elements, comparing them to check which one is
greater.
In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we
We find that 27 is smaller than 33 and these two values must be swapped.
Next we compare 33 and 35. We find that both are in already sorted positions.
Cm_gfgc magadi 15
Then we move to the next two values, 35 and 10.
We know then that 10 is smaller 35. Hence they are not sorted.
We swap these values. We find that we have reached the end of the array. After one
To be precise, we are now showing how an array should look like after each iteration.
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is completely
sorted.
Cm_gfgc magadi 16
Now we should look into some practical aspects of bubble sort.
Algorithm
We assume list is an array of n elements. We further assume that swap function swaps
begin BubbleSort(list)
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort
program
#include <stdio.h>
int main()
int data[100],i,n,step,temp;
scanf("%d",&n);
Cm_gfgc magadi 17
for(i=0;i<n;++i)
scanf("%d",&data[i]);
for(step=0;step<n-1;++step)
for(i=0;i<n-step-1;++i)
temp=data[i];
data[i]=data[i+1];
data[i+1]=temp;
for(i=0;i<n;++i)
printf("%d ",data[i]);
return 0;
Cm_gfgc magadi 18
Complexity Analysis of Bubble Sort
In Bubble Sort, n-1 comparisons will be done in the 1st pass, n-2 in 2nd pass, n-3 in 3rd
pass and so on. So the total number of comparisons will be,
Selection sort
The smallest element is selected from the unsorted array and swapped with the
leftmost element, and that element becomes a part of the sorted array. This
process continues moving unsorted array boundary by one element to the right.
This algorithm is not suitable for large data sets as its average and worst case
complexities are of Ο(n2), where n is the number of items.
Cm_gfgc magadi 19
How Selection Sort Works?
Consider the following depicted array as an example.
For the first position in the sorted list, the whole list is scanned sequentially. The
first position where 14 is stored presently, we search the whole list and find that
10 is the lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the
minimum value in the list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the
list in a linear manner.
We find that 14 is the second lowest value in the list and it should appear at the
second place. We swap these values.
After two iterations, two least values are positioned at the beginning in a sorted
manner.
The same process is applied to the rest of the items in the array.
Cm_gfgc magadi 20
Following is a pictorial depiction of the entire sorting process −
Cm_gfgc magadi 21
Step 5 − Repeat until list is sorted
#include <stdio.h>
int main()
scanf("%d", &n);
scanf("%d", &array[c]);
position = c;
position = d;
if (position != c)
Cm_gfgc magadi 22
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
printf("%d\n", array[c]);
return 0;
Cm_gfgc magadi 23
Insertion Sort Algorithm
which is always sorted. For example, the lower part of an array is maintained to be
sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its
appropriate place and then it has to be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the
sorted sub-list (in the same array). This algorithm is not suitable for large data sets as
its average and worst case complexity are of Ο(n2), where n is the number of items.
How Insertion Sort Works?
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-
list.
Cm_gfgc magadi 24
And finds that 33 is not in the correct position.
It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see
that the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the
By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.
So we swap them.
Cm_gfgc magadi 25
Hence, we swap them too.
We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.
This process goes on until all the unsorted values are covered in a sorted sub-list. Now
Now we have a bigger picture of how this sorting technique works, so we can derive
Cm_gfgc magadi 26
#include <stdio.h>
int main()
scanf("%d", &n);
scanf("%d", &array[c]);
d = c;
temp = array[d];
array[d] = array[d-1];
array[d-1] = temp;
d--;
printf("%d\n", array[c]);
Cm_gfgc magadi 27
return 0;
Searching Algorithms
1 linear search
2 binary search
linear search
In Linear Search the list is searched sequentially and the position is returned if the key
element to be searched is available in the list, otherwise -1 is returned. The search in
Linear Search starts at the beginning of an array and move to the end, testing for a
match at each item.
All the elements preceding the search element are traversed before the search
element is traversed. i.e. if the element to be searched is in position 10, all elements
form 1-9 are checked before 10
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.
Cm_gfgc magadi 28
Assume the element 45 is searched from a sequence of sorted elements 12, 18, 25, 36,
45, 48, 50. The Linear search starts from the first element 12, since the value to be
searched is not 12 (value 45), the next element 18 is compared and is also not 45, by
this way all the elements before 45 are compared and when the index is 5, the element
45 is compared with the search value and is equal, hence the element is found and the
element position is 5.
Step 1: Set i to 1
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
program
#include<stdio.h>
int linear_search(int a[], int, int);
main()
{
int array[100], search, c, n, position;
Cm_gfgc magadi 29
printf("Enter the number of elements in array\n");
scanf("%d",&n);
printf("Enter %d numbers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d",&array[c]);
printf("Enter the number to search\n");
scanf("%d",&search);
position = linear_search(array, n, search);
if ( position == -1 )
printf("%d is not present in array.\n", search);
else
printf("%d is present at location %d.\n", search, position+1);
return 0;
}
int linear_search(int a[], int n, int find)
{
int c;
for ( c = 0 ; c < n ; c++ )
{
if (a[c) == find )
return c;
}
return -1;
}
Cm_gfgc magadi 30
Binary search
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This
search algorithm works on the principle of divide and conquer. For this algorithm to
work properly, the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the
collection. If a match occurs, then the index of item is returned. If the middle item is
greater than the item, then the item is searched in the sub-array to the left of the
middle item. Otherwise, the item is searched for in the sub-array to the right of the
middle item. This process continues on the sub-array as well until the size of the
subarray reduces to zero.
How BinarySearch Works?
For a binary search to work, it is mandatory for the target array to be sorted. We shall
learn the process of binary search with a pictorial example. The following is our sorted
array and let us assume that we need to search the location of value 31 using binary
search.
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.
Now we compare the value stored at location 4, with the value being searched, i.e. 31.
We find that the value at location 4 is 27, which is not a match. As the value is greater
than 27 and we have a sorted array, so we also know that the target value must be in
Cm_gfgc magadi 31
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value
31.
The value stored at location 7 is not a match, rather it is more than what we are looking
for. So, the value must be in the lower part from this location.
We compare the value stored at location 5 with our target value. We find that it is a
match.
Cm_gfgc magadi 32
We conclude that the target value 31 is stored at location 5.
Binary search halves the searchable items and thus reduces the count of comparisons
program
#include<stdio.h>
#include<stdlib.h>
#define size 10
int main() {
int num, i, key, position;
int low, high, list[size];
Cm_gfgc magadi 33
printf("\nEnter the total number of elements");
scanf("%d", &num);
low = 0;
high = num - 1;
if (position != -1) {
printf("\nNumber present at %d", (position + 1));
} else
printf("\n The number is not present in the list");
return (0);
}
if (x == a[mid]) {
return (mid);
} else if (x < a[mid]) {
binsearch(a, x, low, mid - 1);
} else {
binsearch(a, x, mid + 1, high);
}
Cm_gfgc magadi 34
}
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)
int main()
{
// Assume 4x5 sparse matrix
int sparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};
int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
size++;
Cm_gfgc magadi 36
printf("\n");
}
return 0;
}
Cm_gfgc magadi 37
Now put these values in the given formula as below:
LOC (A [3, 2]) = 1000 + 2 [3 (2-1) + (3-1)]
= 1000 + 2 [3 (1) + 2]
= 1000 + 2 [3 + 2]
= 1000 + 2 [5]
= 1000 + 10
= 1010
10 (1,1) 1000
60 (1,2) 1002
30 (1,3) 1004
55 (1,4) 1006
20 (2,1) 1008
90 (2,2) 1010
(2,3) 1012
80
(2,4) 1014
65
(3,1) 1016
50
(3,2) 1018
40
(3,3) 1020
75 1022
(3,4)
79
Suppose we have to find the location of A [3, 2]. The required values are:
Base (A) : 1000
w : 2 (because an integer takes 2 bytes in memory)
N : 4
Cm_gfgc magadi 38
J : 3
K : 2
Now put these values in the given formula as below:
LOC (A [3, 2]) = 1000 + 2 [4 (3-1) + (2-1)]
= 1000 + 2 [4 (2) + 1]
= 1000 + 2 [8 + 1]
= 1000 + 2 [9]
= 1000 + 18
= 1018
Cm_gfgc magadi 39