Data structure unit 2 notes
Data structure unit 2 notes
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.
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}
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.
2
Advantages (ADT):
• Fast, random access of elements or items.
• Very more efficient.
Disadvantages (ADT):
• Slow insertion and deletion of elements.
LA[5]= 10 20 5 1 100
A[0] A[1] A[2] A[3] A[4]
LB (Lower Bound) UB (Upper Bound)
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:
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.
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
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.
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
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
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:
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
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
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
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)
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];
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
Sparse Matrix Representations can be done in many ways following are two common
representations:
1. Array representation 2. Linked list representation
************
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