unit ii-arrays array

39
Cm_gfgc magadi 1 Unit II-ARRAYS 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 Representation of linear arrays in memory 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 LOC (LA [K]) = address of the element LA [K] of the array LA The elements of LA are stored in successive memory cells. The computer does not keep track of the address of every element of LA, but needs to keep track only the address of the first element of LA denoted by,

Upload: others

Post on 10-Dec-2021

21 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Unit II-ARRAYS Array

Cm_gfgc magadi 1

Unit II-ARRAYS

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

Representation of linear arrays in memory

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

LOC (LA [K]) = address of the element LA [K] of the array LA

The elements of LA are stored in successive memory cells. The computer does not keep track of the address of every element of LA, but needs

to keep track only the address of the first element of LA denoted by,

Page 2: Unit II-ARRAYS Array

Cm_gfgc magadi 2

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

LOC (LA[K]) = Base(LA) + w(K – lower bound)

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.

Algorithm 1: (Traversing a Linear Array) 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: “);

Page 3: Unit II-ARRAYS Array

Cm_gfgc magadi 3

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

Let A be a collection of data elements stored in the memory of the

computer. Inserting refers to the operation of adding another element

to the collection A.

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:

INSERT (LA, N, K, ITEM)

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.

Page 4: Unit II-ARRAYS Array

Cm_gfgc magadi 4

1. [Initialize counter] set J:= N

2. Repeat step 3 and 4 while J ≥ K

3. [Move Jt h element downward] Set LA [J+1] := LA[J]

4. [Decrease counter] set J:= J – 1

[End of step 2 loop]

5. [Insert element] set LA[K]:= ITEM

6. [Reset N] set N:= N+1

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

Page 5: Unit II-ARRAYS Array

Cm_gfgc magadi 5

3. Deleting

Deleting refers to the operation of removing one element to the collection A.

Deleting an element at the “end” of the linear array can be easily done with difficulties.

If element at the middle of the array needs to be deleted, then each subsequent elements be moved one location upward to fill up the array.

Algorithm

DELETE (LA, N, K, ITEM)

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

1. Set ITEM:= LA[K]

2. Repeat for J = K to N – 1

[Move J + 1 element upward] set LA[J]:= LA[J+1]

[End of loop]

3. [Reset the number N of elements in LA] set N:= N – 1

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

Page 6: Unit II-ARRAYS Array

Cm_gfgc magadi 6

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

In C, we can define multidimensional arrays in simple words as array of arrays. Data in

multidimensional arrays are stored in tabular form (in row major order).

General form of declaring N-dimensional arrays:

data_type array_name[size1][size2]....[sizeN];

data_type: Type of data to be stored in the array.

Here data_type is valid C data type

array_name: Name of the array

size1, size2,... ,sizeN: Sizes of the dimensions

Examples:

Two dimensional array:

int two_d[10][20];

Three dimensional array:

int three_d[10][20][30];

Page 7: Unit II-ARRAYS Array

Cm_gfgc magadi 7

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.

Example : Sum of two matrices using Two dimensional arrays

// C program to find the sum of two matrices of order 2*2

#include <stdio.h>

int main()

{

float a[2][2], b[2][2], c[2][2];

int i, j;

// Taking input using nested for loop

printf("Enter elements of 1st matrix\n");

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

for(j=0; j<2; ++j)

{

printf("Enter a%d%d: ", i+1, j+1);

scanf("%f", &a[i][j]);

}

// Taking input using nested for loop

printf("Enter elements of 2nd matrix\n");

Page 8: Unit II-ARRAYS Array

Cm_gfgc magadi 8

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]);

}

// adding corresponding elements of two arrays

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

for(j=0; j<2; ++j)

{

c[i][j] = a[i][j] + b[i][j];

}

// Displaying the sum

printf("\nSum Of Matrix:");

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

for(j=0; j<2; ++j)

{

printf("%.1f\t", c[i][j]);

if(j==1)

printf("\n");

}

return 0;

}

Ouput

Page 9: Unit II-ARRAYS Array

Cm_gfgc magadi 9

Enter elements of 1st matrix

Enter a11: 2;

Enter a12: 0.5;

Enter a21: -1.1;

Enter a22: 2;

Enter elements of 2nd matrix

Enter b11: 0.2;

Enter b12: 0;

Enter b21: 0.23;

Enter b22: 23;

Sum Of Matrix:

2.2 0.5

-0.9 25.0

Representation of 2D arrays in memory

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

Page 10: Unit II-ARRAYS Array

Cm_gfgc magadi 10

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.

Page 11: Unit II-ARRAYS Array

Cm_gfgc magadi 11

A 3 x 4 array will stored as below:

Address Calculation in Double (Two) Dimensional Array: While storing the elements of a 2-D array in memory, these are allocated contiguous memory locations. Therefore, a 2-D array must be linearized so as to enable their storage. There are two alternatives to achieve linearization: Row-Major and Column-Major.

Page 12: Unit II-ARRAYS Array

Cm_gfgc magadi 12

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)

Page 13: Unit II-ARRAYS Array

Cm_gfgc magadi 13

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 arranges data in a sequence which makes searching easier.

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.

Well, thank god, computers don't work like this.

Page 14: Unit II-ARRAYS Array

Cm_gfgc magadi 14

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:

1. Time taken to sort the given data.

2. Memory Space required to do so.

Different Sorting Algorithms

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

Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based

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.

Page 15: Unit II-ARRAYS Array

Cm_gfgc magadi 15

How Bubble Sort Works?

We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're

keeping it short and precise.

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

compare 33 with 27.

We find that 27 is smaller than 33 and these two values must be swapped.

The new array should look like this −

Next we compare 33 and 35. We find that both are in already sorted positions.

Page 16: Unit II-ARRAYS Array

Cm_gfgc magadi 16

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

iteration, the array should look like this −

To be precise, we are now showing how an array should look like after each iteration.

After the second iteration, it should look like this −

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.

Page 17: Unit II-ARRAYS Array

Cm_gfgc magadi 17

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

the values of the given array elements.

begin BubbleSort(list)

for all elements of list

if list[i] > list[i+1]

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;

printf("Enter the number of elements to be sorted: ");

scanf("%d",&n);

Page 18: Unit II-ARRAYS Array

Cm_gfgc magadi 18

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

{

printf("%d. Enter element: ",i+1);

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

}

for(step=0;step<n-1;++step)

for(i=0;i<n-step-1;++i)

{

if(data[i]>data[i+1]) /* To sort in descending order, change > to < in this line. */

{

temp=data[i];

data[i]=data[i+1];

data[i+1]=temp;

}

}

printf("In ascending order: ");

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

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

return 0;

}

Page 19: Unit II-ARRAYS Array

Cm_gfgc magadi 19

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,

(n-1) + (n-2) + (n-3) + ..... + 3 + 2 + 1

Sum = n(n-1)/2

i.e O(n2)

Hence the time complexity of Bubble Sort is O(n2).

The main advantage of Bubble Sort is the simplicity of the algorithm.

The space complexity for Bubble Sort is O(1), because only a single additional memory space is required i.e. for temp variable.

Also, the best case time complexity will be O(n), it is when the list is already sorted.

Following are the Time and Space complexity for the Bubble Sort algorithm.

Worst Case Time Complexity [ Big-O ]: O(n2)

Best Case Time Complexity [Big-omega]: O(n)

Average Time Complexity [Big-theta]: O(n2)

Space Complexity: O(1)

Selection sort

Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place

comparison-based algorithm in which the list is divided into two parts, the sorted

part at the left end and the unsorted part at the right end. Initially, the sorted

part is empty and the unsorted part is the entire list.

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.

Page 20: Unit II-ARRAYS Array

Cm_gfgc magadi 20

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.

Page 21: Unit II-ARRAYS Array

Cm_gfgc magadi 21

Following is a pictorial depiction of the entire sorting process −

Now, let us learn some programming aspects of selection sort.

Algorithm

Step 1 − Set MIN to location 0 Step 2 − Search the minimum element in the list Step 3 − Swap with value at location MIN Step 4 − Increment MIN to point to next element

Page 22: Unit II-ARRAYS Array

Cm_gfgc magadi 22

Step 5 − Repeat until list is sorted

#include <stdio.h>

int main()

{

int array[100], n, c, d, position, swap;

printf("Enter number of elements\n");

scanf("%d", &n);

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

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

scanf("%d", &array[c]);

for (c = 0; c < (n - 1); c++)

{

position = c;

for (d = c + 1; d < n; d++)

{

if (array[position] > array[d])

position = d;

}

if (position != c)

Page 23: Unit II-ARRAYS Array

Cm_gfgc magadi 23

{

swap = array[c];

array[c] = array[position];

array[position] = swap;

}

}

printf("Sorted list in ascending order:\n");

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

printf("%d\n", array[c]);

return 0;

}

Complexity Analysis of Selection Sort Selection Sort requires two nested for loops to complete itself, one for loop is in the function selectionSort, and inside the first loop we are making a call to another function indexOfMinimum, which has the second(inner) for loop.

Hence for a given input size of n, following will be the time and space complexity for selection sort algorithm:

Worst Case Time Complexity [ Big-O ]: O(n2)

Best Case Time Complexity [Big-omega]:(n2)

Average Time Complexity [Big-theta]:(n2)

Space Complexity: O(1)

Page 24: Unit II-ARRAYS Array

Cm_gfgc magadi 24

Insertion Sort Algorithm

This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained

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?

We take an unsorted array for our example.

Insertion sort compares the first two elements.

It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-

list.

Insertion sort moves ahead and compares 33 with 27.

Page 25: Unit II-ARRAYS Array

Cm_gfgc magadi 25

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

sorted sub-list remains sorted after swapping.

By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.

These values are not in a sorted order.

So we swap them.

However, swapping makes 27 and 10 unsorted.

Page 26: Unit II-ARRAYS Array

Cm_gfgc magadi 26

Hence, we swap them too.

Again we find 14 and 10 in an unsorted order.

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

we shall see some programming aspects of insertion sort.

Algorithm

Now we have a bigger picture of how this sorting technique works, so we can derive

simple steps by which we can achieve insertion sort.

Step 1 − If it is the first element, it is already sorted. return 1; Step 2 − Pick next element Step 3 − Compare with all elements in the sorted sub-list Step 4 − Shift all the elements in the sorted sub-list that is greater than the value to be sorted Step 5 − Insert the value Step 6 − Repeat until list is sorted

Insertion sort algorithm implementation in C

/* Insertion sort ascending order */

Page 27: Unit II-ARRAYS Array

Cm_gfgc magadi 27

#include <stdio.h>

int main()

{

int n, array[1000], c, d, temp;

printf("Enter number of elements\n");

scanf("%d", &n);

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

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

scanf("%d", &array[c]);

for (c = 1 ; c <= n - 1; c++) {

d = c;

while ( d > 0 && array[d-1] > array[d]) {

temp = array[d];

array[d] = array[d-1];

array[d-1] = temp;

d--;

}

}

printf("Sorted list in ascending order:\n");

for (c = 0; c <= n - 1; c++) {

printf("%d\n", array[c]);

}

Page 28: Unit II-ARRAYS Array

Cm_gfgc magadi 28

return 0;

}

Complexity Analysis of Insertion Sort

As we mentioned above that insertion sort is an efficient sorting algorithm, as it does not run on preset conditions using for loops, but instead it uses one while loop, which avoids extra steps once the array gets sorted.

Even though insertion sort is efficient, still, if we provide an already sorted array to the insertion sort algorithm, it will still execute the outer for loop, thereby requiring n steps to sort an already sorted array of n elements, which makes its best case time complexity a linear function of n.

Worst Case Time Complexity [ Big-O ]: O(n2)

Best Case Time Complexity [Big-omega]: O(n)

Average Time Complexity [Big-theta]: O(n2)

Space Complexity: O(1)

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.

Page 29: Unit II-ARRAYS Array

Cm_gfgc magadi 29

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.

Linear search Algorithm

Linear Search ( Array A, Value x) 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;

Page 30: Unit II-ARRAYS Array

Cm_gfgc magadi 30

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;

}

Page 31: Unit II-ARRAYS Array

Cm_gfgc magadi 31

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 Binary Search 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.

First, we shall determine half of the array by using this formula −

mid = low + (high - low) / 2

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

the upper portion of the array.

Page 32: Unit II-ARRAYS Array

Cm_gfgc magadi 32

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.

Hence, we calculate the mid again. This time it is 5.

We compare the value stored at location 5 with our target value. We find that it is a

match.

Page 33: Unit II-ARRAYS Array

Cm_gfgc magadi 33

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

to be made to very less numbers.

Algorithm Algorithm

BINSRCH (a, n, x)

// array a(1 : n) of elements in increasing order, n 0,

// determine whether ‘x’ is present, and if so, set j such that x = a(j)

// else return j

{

low :=1 ; high :=n ;

while (low < high) do

{

mid :=|(low + high)/2|

if (x < a [mid]) then high:=mid – 1;

else if (x > a [mid]) then low:= mid + 1

else return mid;

}

return 0;

}

program #include<stdio.h> #include<stdlib.h> #define size 10 int binsearch(int[], int, int, int); int main() { int num, i, key, position; int low, high, list[size];

Page 34: Unit II-ARRAYS Array

Cm_gfgc magadi 34

printf("\nEnter the total number of elements"); scanf("%d", &num); printf("\nEnter the elements of list :"); for (i = 0; i < num; i++) { scanf("%d", &list[i]); } low = 0; high = num - 1; printf("\nEnter element to be searched : "); scanf("%d", &key); position = binsearch(list, key, low, high); if (position != -1) { printf("\nNumber present at %d", (position + 1)); } else printf("\n The number is not present in the list"); return (0); } // Binary Search function int binsearch(int a[], int x, int low, int high) { int mid; if (low > high) return -1; mid = (low + high) / 2; if (x == a[mid]) { return (mid); } else if (x < a[mid]) { binsearch(a, x, low, mid - 1); } else { binsearch(a, x, mid + 1, high); }

Page 35: Unit II-ARRAYS Array

Cm_gfgc magadi 35

}

Sparse Matrix and its representations

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. 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.. Example:

0 0 3 0 4

0 0 5 7 0

0 0 0 0 0

0 2 6 0 0

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

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)

// C++ program for Sparse Matrix Representation // using Array

Page 36: Unit II-ARRAYS Array

Cm_gfgc magadi 36

#include<stdio.h> 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++; // number of columns in compactMatrix (size) must be // equal to number of non - zero elements in // sparseMatrix int compactMatrix[3][size]; // Making of new matrix int k = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) if (sparseMatrix[i][j] != 0) { compactMatrix[0][k] = i; compactMatrix[1][k] = j; compactMatrix[2][k] = sparseMatrix[i][j]; k++; } for (int i=0; i<3; i++) { for (int j=0; j<size; j++) printf("%d ", compactMatrix[i][j]);

Page 37: Unit II-ARRAYS Array

Cm_gfgc magadi 37

printf("\n"); } return 0; }

Examples for address calculation in 2d array

1. In case of Column Major Order: The formula is: LOC (A [J, K]) = Base (A) + w [M (K-1) + (J-1)] Here LOC (A [J, K]) : is the location of the element in the Jth row and Kth column. Base (A) : is the base address of the array A. w : is the number of bytes required to store single element of the array A. M : is the total number of rows in the array. J : is the row number of the element. K : is the column number of the element. E.g. A 3 x 4 integer array A is as below:

Subscript Elements Address

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) M : 3 J : 3 K : 2

10

20

50

60

90

40

30

80

75

55

65

79

(1,1)

(2,1) (3,1) (1,2) (2,2) (3,2) (1,3)

(2,3) (3,3) (1,4) (2,4) (3,4)

1000 1002 1004 1006

1008 1010 1012 1014 1016 1018

1020 1022

Page 38: Unit II-ARRAYS Array

Cm_gfgc magadi 38

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

2. In case of Row Major Order: The formula is: LOC (A [J, K]) = Base (A) + w [N (J-1) + (K-1)] Here LOC (A [J, K]) : is the location of the element in the Jth row and Kth column. Base (A) : is the base address of the array A. w : is the number of bytes required to store single element of the array A. N : is the total number of columns in the array. J : is the row number of the element. K : is the column number of the element. E.g. A 3 x 4 integer array A is as below:

Subscript Elements Address

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

1000

1002 1004 1006 1008 1010 1012

1014 1016 1018 1020 1022

(1,1) (1,2) (1,3) (1,4)

(2,1) (2,2) (2,3) (2,4) (3,1) (3,2)

(3,3) (3,4)

10

60

30

55

20

90

80

65

50

40

75

79

Page 39: Unit II-ARRAYS Array

Cm_gfgc magadi 39

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