DS Chapter 2
DS Chapter 2
UNIT – 02
ARRAYS
Definition of Array:
The collection of homogeneous elements which has same data type and same name.
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple
items of the same type together.
Properties of an Array
1. All elements of an array must be of same data type.
2. Each element of an array is referred to be specifying the array name followed by one or more
subscript.
3. Each subscript must be expressed as a positive integer.
4. The subscript will begin with the number 0.
5. Array elements are always stored in sequential memory locations.
Types of Arrays
Arrays can be classified as follows
1. One–Dimensional Array / 1-D Array
2. Two–Dimensional Array / 2-D Array
3. Multidimensional Array
1. One-Dimensional Array / 1-D Array:
It is a collection of homogeneous elements and same data type and same name, and with only
one subscript is called as one-dimensional array.
Syntax or the general form or the declaration of one-dimensional array is
To declare an array,
1. Here datatype declares the type of elements to be stored in the array such as int, float, char,….
2. Array name is the name of the array
3. Size specifies maximum number of elements that can be stored in the array.
datatype arrayname[size];
Chithra T R Page 1
DATA STRUCTURE
where
1. Datatype can be int, float, double, char etc.
2. array_ name should be a valid variable name.
3. size is an integer value.
4. Size of an array must not be in negative value.
End of the Statement
2. Two-Dimensional Array
The two-dimensional array can be defined as an array of arrays.
The 2D array is organized as matrices which can be represented as the collection of rows and
columns.
However, 2D arrays are created to implement a relational database looks like data structure.
It provides ease of holding the bulk of data at once which can be passed to any number of functions
wherever required.
Declaring of Two-Dimensional Array
The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];
Consider the following example
Initialization of 2-D Array
There are two ways to initialize a two-dimensional array during declaration.
Chithra T R Page 2
DATA STRUCTURE
int disp[2][4]={
Chithra T R Page 3
DATA STRUCTURE
{10,11,12,13}
{14,15,16,17}
Rows, a[0] a[1] a[2] a[3]
}; Columns
(Or) a[0] 10 11 12 13
int disp[2][4]={10,11,12,13,14,15,16,17}; a[1] 14 15 16 17
3. Multi-Dimensional Array
Collection of homogeneous elements which has same datatype and same name with more than two
subscripts is called as Multi-Dimensional Array.
Operations of arrays
There are six types of operations of arrays:
1. Traversal: processing each element in the array or to visit the element stored in it. Traversing an
array means going through each element of an array exactly once is called as traversal.
2. Searching: Finding the location of the element with a given value in the array or the search
operation is used to find a particular data item or element in an array is called searching.
3. Insertion: Adding a new element into an array. Based on the requirement, a new element can be
added at the beginning, end or any given index of array is called insertion.
4. Deletion: Removing an element from an array is called deletion.
5. Sorting: Arranging the element in some type of order or the processing of arranging the data in
ascending or descending order. There are several types of sorting in data structures namely- bubble
sort, insertion sort, selection sort, merge sort, quick sort etc.
6. Merging: Combining of two arrays into single array or when two or more arrays are merged to form
a bigger array containing all the items of the merged arrays is called merging.
Chithra T R Page 4
DATA STRUCTURE
Chithra T R Page 5
DATA STRUCTURE
Chithra T R Page 6
DATA STRUCTURE
Chithra T R Page 7
DATA STRUCTURE
Sorting
Arranging the elements into ascending or descending order is called sorting.
Arranging the unordered elements in an array in ordered way is called sorting.
Types of Sorting
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Quick Sort
5. Merge 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 element are swapped if they are not
in order.
Algorithm of Bubble Sort:
Step 1: for pass=1 to n-1
Step 2: for j=0 to n-pass-1
Step 3: if a[j]>a[j+1] then
Temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
Step 4: end for
Step 5: end for
//Program to perform Bubble Sort technique.
#include<stdio.h>
#include<conio.h>
void main()
{
int , i,n,temp,j,arr[10];
clrscr();
printf(“enter the number of elements;”);
scanf(“%d”,&n);
printf(“\n enter the elements in array:\n”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
for(i=0;i<n;i++)
Chithra T R Page 9
DATA STRUCTURE
{
for(j=0;j<n;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf(“\n the array sorted in ascending order is:\n”);//traversing part
for(i=0;i<n;i++)
printf(„\t%d”,arr[i]);
getch();
}
}
Output: Enter the number of elements: 6
Enter the elements in array:
99 33 6 77 3 0
The array sorted in ascending order:
0 3 6 33 77 99
Chithra T R Page 10
DATA STRUCTURE
Selection Sort
It is a selection of an element and placing it in an proper position.
In selection sort first will search the smallest element in array and interchange with the first element.
Then search the second smallest element and interchange with the second element and continuous
the process until all the elements are completed.
The method of selection sort relays heavily on a comparison mechanism to achieve its goal.
Algorithm:
1. set location=0
2. Repeat step 3 and 4 for k=0 to n-1
3. Loc=call MIN (a,k,n)
4. (Interchange A[k] and A[loc])
i. Temp=A[k]
ii. A[k]=A[loc]
iii. A[loc]=temp
5. EXIT
Algorithm min(a[0 ------a-1];m,n)
1. Set min=A[k],loc=k
2. Repeat step3 for j=k+1 to n-1
3. if min>A[j]
a. min =A[j]
b. loc =j
4. Return Loc;
Chithra T R Page 11
DATA STRUCTURE
Chithra T R Page 12
DATA STRUCTURE
Chithra T R Page 13
DATA STRUCTURE
Insertion Sort
1. The insertion sort inserts each element in appropriate position.
2. This is same as playing card in which we insert a card in proper position.
3. The insertion sort is effectively only when the number to be sorted all very less.
Algorithm:
1. Repeat step2 to 3 for pass=1 to n-1
2. set k=A[pass]
3. Repeat step 4 for j=pass-1 to 0
4. if (k<A[j])
a. A [j+1] = A[j]
b. A [j+1] = k
5. EXIT
//Program of Insertion Sort:
#include<stdio.h>
#include<conio.h>
void main()
{
int arr [10],i,j,n,temp;
clrscr();
printf(“enter the number of elements;”);
scanf(“%d”,&n);
printf(“\n enter the elements in array:\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
for(i=1;i<=n-1;i++)
{
j=i;
while (j<0; && arr[j-1]>arr[j])
{
temp=arr[j];
arr[j] = arr [j-1];
arr [j-1] = temp;
j--;
}
}
for(i=0;i<n;i++)
{
printf(„sorted list is = %d\n”, arr[i]);
}
Chithra T R Page 14
DATA STRUCTURE
getch();
}
Output: Enter the size of the array: 6
Enter the elements in array:
381604
Sorted list is= 0
Sorted list is= 1
Sorted list is= 3
Sorted list is= 4
Sorted list is= 6
Sorted list is= 8
Chithra T R Page 15
DATA STRUCTURE
Quick Sort
1. It is one of the most popular sorting mechanism used to arrange the element in an ascending order.
2. In this mechanism it uses divide and conquer technique.
3. Here the 1st element of the array is selected as a key element or pivot (IMP) element.
4. Next remaining elements are grouped into two partition . Such as left and right partition.
5. Left partition contains elements smaller than the pivot element.
6. Right partition contains element larger than the pivot element.(Value>key) (Value<key)
Repeat the same process in left and right partition, until the end of array.
Another important point: When left and right element crosses each other then right element will swap or
interchange with the pivot element.
Algorithm For Sorting:
Step 1: if (low<high) then
Step 2: j=partition(A,low,high)
Step 3: Quick_ sort(A,low,j-1)
Step 4: Quick_ sort(A,j+1,high)
Step 5: End if
Step 6: EXIT
Algorithm of Quick Sort for Partition:
Step 1: set pivot=low
I=low
J=high
Step 2: Repeat step 3 to step 6 while(i<j)
Step 3: Repeat step 4 while (( i< high ) && (A[i]<=[pivot]))
Step 4: i=i+1
Step 5: Repeat step 6 while (A[j]>A[pivot])
Step 6: j=j-1
Step 7: if(i<j)
Swap a[i] & a[j]
End of step 2 while
Step 8: swap a[j] & pivot
Step 9: Return(j)
//Program Of Quick Sort:
#include<stdio.h>
#include<conio.h>
void quicksort(int a[25],int f int l)
{
int i,j,pivot,jump;
Chithra T R Page 16
DATA STRUCTURE
if(f<l)
{
pivot=f;
i=f;
j=l;
while(i<j)
}
while(a[i]<=a[pivot] && i<l))
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,f,j-1);
quicksort(a,j+1,f);
}
}
void main()
{
int i,n,a[25],l;
clrscr():
printf(”enter the size of an array\n”);
Chithra T R Page 17
DATA STRUCTURE
scanf(“%d”,&n);
Chithra T R Page 18
DATA STRUCTURE
i=i+1
else
c[k]=a[j]
k=k+1
j=j+1
end if
end while (step 2)
Step 4: while (i<=mid)
c[k]=a[i]
k=k+1
i=i+1
end while (Step 4)
Step 5: while (j<=high)
c[k]=a[j]
k=k+1
j=j+1
end while (step 5)
Step 6: for i=low to k-1
a[i]=c[i]
end for (Step 6)
Step 7: return
//Program Of Merge Sort:
#include<stdio.h>
#include<conio.h>
void simple-merge(int a[],int low ,int mid ,int high)
{
int i=low,j=mid+1,k=low ,c[10];
while(i<=mid && j<=high)
{
if(a[i]<a[j])
{
Chithra T R Page 19
DATA STRUCTURE
c[k++]=a[i++];
}
else
{
c[k++]=a[j++];
}
}
while (i<=mid)
{
c[k++]=a[i++];
}
while(j<=high)
{
c[k++]=a[j++];
}
for(i=low;i<=high;i++0
{
a[i]=c[i]
}
}
void mergesort (int a[] ,int low ,int high)
{
int mid ;
if (low<high)
{
mid =(low+high)/2;
merge_sort(a,low,mid0;
merge_sort(a,mid+1,high);
simple_merge (a,low,mid ,high);
}
}
void main()
{
int a[10],n,i;
clrscr();
printf(”enter the size of an array\n”);
scanf(“%d”,&n);
printf(„enter %d array elements\n”,n);
for(i=0;i<n;i++)
Chithra T R Page 20
DATA STRUCTURE
{
scanf(“%d‟,&a[i]);
}
merge-sort(a,0,n-1);
printf(“\n the sorted elements are.. :\n”);//traversing part
for(i=0;i<n;i++)
printf(„\t%d”,arr[i]);
getch();
}
Output: Enter the size of the array: 5
Enter the array elements:
99 70 3 88 1
The sorted elements are
1 3 70 88 99
Chithra T R Page 21
DATA STRUCTURE
Searching
Searching refers to finding for an element in any list.
Searching in data structure refers to the process of finding location LOC of an element in a list. This
is one of the important parts of many data Structure algorithms, as one operation can be performed
on a element if and only if we find it.
There are 2 types of searching they are:
1) Linear Search
2) Binary search
Chithra T R Page 22
DATA STRUCTURE
Linear Search
Linear search is a very simple 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 the that particular item is returned, otherwise the
search continues till the end of the data collection.
Algorithm
Linear search (A [] , n , key)
Let A [] be a linear array with n elements and key is an element to be searched in A [].
Step 1: Set i=0
Step 2: while (i<n) do
If A[i] = = key then
Return i; // key found at I th location
End while
Step 3: Return-1; //key not found
//Program of Linear Search
#include<stdio.h>
#include<conio.h>
void main()
{
int arr [50],i,n,key;
clrscr();
printf(“enter the required array size;”);
scanf(“%d”,&n);
printf(“\n enter the elements in array:\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
printf(“the entered array elements are\n”);
for(i=0;i<n;i++)
{
printf(“%d\t”,a[i]);
}
printf(“enter the key element you want to search\n”);
scanf(“%d”,&key);
for(i=0;i<n;i++)
{
if(a[i]= = key)
{
printf(„search is successful\n”);
Chithra T R Page 23
DATA STRUCTURE
Chithra T R Page 24
DATA STRUCTURE
Binary Search
Binary search is the search technique that works efficiently on sorted lists. Hence, to search an
element into some list using the binary search technique, we must ensure that the list is sorted.
Binary search follows the divide and conquer approach in which the list is divided into two halves,
and the element is compared with the middle element of the list.
Binary search is one of the best suits to solve the above complexity problem.
0 1 2 3 4 5 6 7 8
Low left Mid Right high
If (key>mid) --- R Mid = Low + High/2
If (key<mid) --- L
Algorithm-Binary Search
(A[0---n-1],key)
Input: Given an array A of n elements is sorted under and key is an element to be sorted.
Output: Return the position of item element if successful and returns-1 otherwise.
Step 1: set first=0, last =n-1;
Step 2: repeat step 3 until (first,=last)
Step 3: find the middle location 9mid)=(f+l)/2
if key is equal to a[mid]
else if (key<a[mid]) then search element from first to mid-1
last=mid-1
else search element from mid+1 to last first= mid+1
end while
Step 4: return-1
Program Of Binary Search:
#include<stdio.h>
#include<conio.h>
void main()
{
int arr [50],i,n,low,mid,high,key;
clrscr();
printf(“enter the number of elements;”);
Chithra T R Page 25
DATA STRUCTURE
scanf(“%d”,&n);
printf(“\n enter the elements in array:\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
printf(“the entered array elements are\n”);
for(i=0;i<n;i++)
{
printf(“%d\t”,a[i]);
}
printf(“enter the key element you want to search\n”);
scanf(“%d”,&key);
low=0;
high=n-1;
while (low<=high)
{
mid=(low+high)/2;
if(key= =a[mid])
{
printf(„search is successful\n”);
printf(“key element %d found at %d position”, key ,i);
break;
}
else if (key> a[mid ])
{
low=mid+1;
}
else
{
high=mid-1;
}
}
if (low>high)
{
printf(“search is unsuccessfull\n”);
printf(“key element %d not found key”);
}
getch();
}
Chithra T R Page 26
DATA STRUCTURE
Chithra T R Page 27
DATA STRUCTURE
2D array initialization:
An array can either be initialized during or after declaration. The format of initializing an array during
declaration is as follows:
type arr[row_size][column_size] = {{elements}, {elements} ... }
int arr[3][5] = {{5, 12, 17, 9, 3}, {13, 4, 8, 14, 1}, {9, 6, 3, 7, 21}};
Program of Multi-Dimensional Array
#include<stdio.h>
#include<conio.h>
int main()
{
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2d array
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
Output: arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
Chithra T R Page 28
DATA STRUCTURE
Sparse Matrix
Matrices which contain high number of zero entries are called as sparse matrices.
In simple terms the matrix which contains more zero elements than non zero elements are referred as
sparse matrix.
In this above example there are 20 elements in which 13 elements are zeros and remaining 7
elements are non-zeros.
Program to check whether the given matrix is sparse matrix or not
#include<stdio.h>
#include<stdlib.h>
int main(){
int row,col,i,j,a[10][10],count = 0;
printf("Enter row\n");
scanf("%d",&row);
printf("Enter Column\n");
scanf("%d",&col);
printf("Enter Element of Matrix1\n");
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
scanf("%d",&a[i][j]);
}
}
printf("Elements are:\n");
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
/*checking sparse of matrix*/
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
Chithra T R Page 29
DATA STRUCTURE
if(a[i][j] == 0)
count++;
}
}
if(count > ((row * col)/2))
printf("Matrix is a sparse matrix \n");
else
printf("Matrix is not sparse matrix\n");
}
Output: When the above program is executed, it produces the following result −
Run 1:
Enter row
3
Enter Column
2
Enter Element of Matrix1
102020
Elements are:
10
20
20
Matrix is not sparse matrix
Run 2:
Enter row
3
Enter Column
2
Enter Element of Matrix1
100000
Elements are:
10
00
00
Matrix is a sparse matrix
Chithra T R Page 30
DATA STRUCTURE
Chithra T R Page 31