0% found this document useful (0 votes)
6 views83 pages

DS Module 1

Uploaded by

lohi18th2005cn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views83 pages

DS Module 1

Uploaded by

lohi18th2005cn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 83

R L JALAPPA INSTITUTE OF TECHNOLOGY

Dept.. of Computer Science & Engg.

Module 1
Data Structures and Applications

Vinaykumar Y B
Assistant Professor

Department
1 of Computer Science, RLJIT
Outline
 Introduction:
 Data Structures, Classifications (Primitive & Non Primitive).Data structure
Operations
 Review of Arrays
 Structures, Self-Referential Structures, and Unions
 Pointers
 Dynamic Memory Allocation Functions
 Representation of Linear Arrays in Memory
 Dynamically allocated arrays
 Array Operations:
 Traversing, Inserting, Deleting, Searching and Sorting
 Multidimensional Arrays
 Polynomials
 Sparse Matrices

Department of Computer Science, RLJIT 2


Data Structures
 Data structure is a Specific way to store and organize data in a
computer's memory so that these data can be used efficiently
later.

 Data may be arranged in many different ways such as the


logical or mathematical model, for a particular organization
data is termed as a data structure.

Department of Computer Science, RLJIT 3


Classification of Data Structure
 Data structure are classified into Primitive and Non-Primitive
data structure.

Department of Computer Science, RLJIT 4


Classification of Data Structure
Primitive Data Structures
Data structures that normally manipulated by machine-level
instructions are known as primitive data structures.

Examples: Integer, float, character and pointers

These data types are available in most programming languages as


built in data types.

Department of Computer Science, RLJIT 5


Classification of Data Structure
Non Primitive Data Structures
Data structures that are not manipulated by machine-level instructions
are known as non primitive data structures.

Non Primitive Data Structures is classified into:


Linear Data Structure: Elements of data structure are stored in a
linear or sequential order.
Examples: Arrays, Linked Lists, Stacks, Queues

Non-linear Data Structure: If the elements of a Data Structure are


not stored in a sequential order, then it is a Non-Linear Data Structure.
Examples: Trees, Graphs
Department of Computer Science, RLJIT 6
Classification of Data Structure
Linear Data Structure Non-Linear Data Structure

Every item is related to its previous and Every item is attached with many other
next item. items

Data is arranged in linear sequence. Data is not arranged in sequence

Data items can be traversed in a single run. Data cannot be traversed in a single run.

Examples: Array, Stack, Queue, Linked Examples: Tree, Graph.


List.

Implementation is Easy. Implementation is Difficult


Department of Computer Science, RLJIT 7
Data structure Operations
Some specific operations applied to data available in the data
structures.
The different data structure operations are listed below:
• Traversing : Accessing each record(element) exactly once so that
certain items may be processed.
• Searching : Finding the location of the record with a given key
value.
• Insertion : Adding a new record into the data structure.
• Deletion : Removing a record from the structure.
• Sorting : Arranging the record in ascending or descending order.
• Merging : Combing two data structures.

Department of Computer Science, RLJIT 8


Review of Arrays
• An array is collection of similar data items.
• The elements of an array are of same type and each element can
be accessed using same name, but with different index value.
• An array is defined as collection/set of variables of the same type
under single variable name, and array is linear data structure
that can store fixed number of values.

• Arrays are of 2 types:


• Single/One dimensional array
• Multi dimensional array

Department of Computer Science, RLJIT 9


Review of Arrays
• Formally, an array is defined as a set of pairs <index, value>,
where index is position and value is data stored in position index.

Example: Array of marks[5];

Department of Computer Science, RLJIT 10


Review of Arrays
ADT(Abstract Data Type) for Array:
An ADT of array provides details of array implementation and
various operations that can be performed on an array.
Structure Array is
Object : A set of pairs <index, value> where value is data stored at index
position in an array, for one dimensional, array index values are {0, 1, 2, 3,
……. n-1}for two dimensional, array index values are { (0, 0), (0, 1), (0, 2),
(1,0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)}
Functions: A € Array, i € index, x € item, n € integer
Array Create (n, A) ::= return array A of size n.

item Retrieve (A, i) ::= if i € index then return item stored in array
A at index position i.
else return error
Array Store(A, i ,x) ::= If i € index then return array A , by storing
x at index position i in A
else return
Department error
of Computer Science, RLJIT 11
end Array
Review of Arrays
SINGLE OR ONE DIMENSIONAL ARRAY
• A single or one dimensional array is a linear list consisting of
related elements of same type.
• In memory, all the elements are stored in continuous memory-
location one after the other.
Syntax :
data_type array_name [size];
Example:
int a[3];
char carr[20] ;
float b[3] ;
Initialization of Array :
int a[5] = { 4, 5, 7, Department
3, 9}; of Computer Science, RLJIT
12
Example :
Review of Arrays
Multi-Dimensional Array
(Array of Array) Array having more than one subscript is called Multi-
Dimensional array.
Multi Dimensional Array is also called as Matrix.
Ex: Two dimensional array, Three dimensional array, four dimensional array
etc.
2D array
The Two Dimensional array is used for representing the elements of the array in
the form of the rows and columns and these are used for representing the matrix.
Two Dimensional Array uses the two subscripts for declaring the elements of the
Array
Syntax :
data_type array_name[num_of_rows][num_of_column];
Example:
int a[2][2];
Array initialization syntax: Different ways to initialize two dimensional array
int arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};
Department of Computer Science, RLJIT 14
Structures
A structure is a user-defined data type.
It is defined as a group of dissimilar or heterogeneous data items, where items
can be of a different data type.
Structure declaration:
Syntax :
struct structure_name
Example:
{ struct student
type1 var1; {
type2 var2; int rno;
int age;
..............................
char name[30];
typeN varN; };
};
Where
struct is a keyword(for structure)
type1, type2, ….typeN are standard data types like int, float, char, double
var1, var2,…varN are member of the structures.
Department of Computer Science, RLJIT 15
structure_name or tagname is any identifier
Structures
Example to define structure for employee in c.

struct employee How to create a structure?


‘struct’ keyword is used to create a structure..
{
int id;
char name[50];
float salary;
};

Here, struct is the keyword, employee is the tag name of


structure; id, name and salary are the members or fields of the
structure.

Department of Computer Science, RLJIT 16


Structures
Declaring structure variable
• User can declare variable for the structure, so that member of
structure can be access easily.
• To allocate the memory for the structure, we have to declare
the variable as shown.
struct structure_name structure_variable_names;
Example:
struct student cse, ise;
Once structure variables are declared, compiler allocated
memory for the structure variables.

Department of Computer Science, RLJIT 17


Structures
Two ways to declare variables:
Method 1
Method 2
struct student
struct student
{
{
int rlno;
int rlno;
int marks;
int marks;
char name[20];
char name[20];
};
} cse, ise; // global structure variables
struct student cse, ise;

Memory Representation of Structure: cse and ise is as follows.


24 bytes of memory is allocated each for the structure variable cse
and ise.
Department of Computer Science, RLJIT 18
// A variable declaration with structure declaration.
struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types


struct Point
{
int x, y;
};

int main()
{
struct Point p1; // The variable p1 is declared like a normal
variable
}
How to initialize structure members?
Structure members cannot be initialized with declaration.
For example the following C program fails in compilation.

struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};

The reason for above error is simple, when a datatype is


declared, no memory is allocated for it.
Memory is allocated only when variables are created.
Structure members can be initialized using curly braces
‘{}’.
For example, following is a valid initialization
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1};
// A valid initialization. member x gets value 0 and
//y gets value 1. The order of declaration is followed.
}
Structures
Structure intialization:
Assigining values to the structre
variable.
Method 1 Method 2
struct student
{ struct student
int rlno; {
int marks; int rlno;
char name[20]; int marks;
}; char name[20];
struct student cse = { 01, 99, “Kumar”}; } cse= { 01, 99, “Kumar”};

Department of Computer Science, RLJIT 22


Structures
Structure intialization:
Assigining values to the structre
Method 2
variable.
Method 1
struct student
struct student
{
{
int rlno;
int rlno;
int marks;
int marks;
char name[20];
char name[20];
} cse= { 01, 99, “Kumar”};
};
struct student cse = { 01, 99, “Kumar”};

Department of Computer Science, RLJIT 23


Structures
Accessing members of structure
• There are two ways to access structure members:

–By . (member or dot operator)

–By -> (structure pointer operator)

• The code to access the id member of p1 variable by .


(member) operator.
p1.id
cse.marks
Department of Computer Science, RLJIT 24
How to access structure elements or members?
Example 1:
#include<stdio.h>
struct Point
{
int x, y;
};

int main()
{
struct Point p1 = {0, 1};

// Accessing members of point p1


p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);
return 0;
}
Output:
x = 20, y = 1
Example 2: Accessing members of structure
#include<stdio.h>
struct Vehicle
{
int wheels;
char vname[20];
char color[10];
}v1 = {4," Swift Desire "," White "};

int main()
{
//Struct vehicle v1;
printf(Vehicle No of Wheels : %d",v1.wheels);
printf(Vehicle Name : %s",v1.vname);
printf(Vehicle Color : %s",v1.color);
return(0); Output
} Vehicle No of Wheels : 4
Vehicle Name : Swift Desire
VehicleColor:White
Structures
Array of Structures:
struct student ∙ In this example we have declare a structure variable
{ (i.e s).
char name[20]; ∙ Using this structure variable (i.e s) we can store the
int usn; information of only one student.
int marks; ∙ If we want to store information of more number of
}s; students then we declare structure variable as an
Array.

∙ struct student ∙
∙ { ∙ In this example we have declare a structure
∙ char name[20]; variable as an Array i.e s[10].
∙ int usn; ∙ Using this s[10] we can store the information of
∙ int marks; 10 students.
∙ }s[10]; ∙

Department of Computer Science, RLJIT 27


Structures
Nested Structure
• Nested structure is a structure that contains another structure as its
member.
• There are two ways of creating nested structure.
– Declaring a structure inside another structure.
– Structure variable as data member inside the structure.

Department of Computer Science, RLJIT 28


Structures
Declaring a structure inside another structure Structure variable as data member inside the
Nested Structure structure
struct student struct DOB
{ {
char name[20]; int dd;
int usn; int mm;
int marks; int yy;
};
struct DOB
{ struct student
int dd; {
int mm; char name[20];
int yy; int usn;
}date; int marks;
}s; struct DOB date;
}s;

Accessing the members of Structure DOB


Accessing the members of Structure DOB
s.date.dd;
s.date.dd;
s.date.mm;
s.date.mm;
Department of Computer Science, RLJIT
s.date.yy;
s.date.yy; 29
Structures
Type defined Structure:
The structure definition associated with keyword typedef is called type-defined structure.
This is the most powerful way of defining the structure. This can be done using two methods:
Method 2
Method 1
struct structre_name
typedef struct
{
{
type1 member1;
type1 member1;
type2 member2;
type2 member2;
.
.
.
.
};
}typedef_name;
typedef struct structre_name typedef_name;
Example:
Example:
typedef struct
struct student
{
{
char name[20];
char name[20];
int age;
int age;
int rlno;
int rlno;
}student;
};
Create variables:
Create variables:
typedef_name variables;
typedef struct structure_name st;
Example Department of Computer Science, RLJIT 30
Example st cse, ise;
student cse, ise;
Self-Referential Structures
Self Referential Structure is the data structure in which the pointer
refers to the same type of structure, as their member.
struct tag Example:
{
struct node
member 1;
member 2; {
………… ………… int data;
struct tag *name; struct node *ptr;
};
};
• The structure of type tag contains a member, “name‟ which is a
pointer to structure of type tag .
• Thus tag is a self referential structure.
Department of Computer Science, RLJIT 31
Self-Referential Structures
Types of Self Referential Structures
1. Self Referential Structure with Single Link
2. Self Referential Structure with Multiple Links

Applications: Self referential structures are very useful in creation of


other complex data structures like:

– Linked Lists
– Stacks
– Queues
– Trees
– Graphs etc

Department of Computer Science, RLJIT 32


Self-Referential Structures
Advantages:
1. Unlike static data structures, self referential structure can
dynamically be expanded. Thus, require dynamic memory
allocation functions (malloc, free) to explicitly obtain and release
memory.
2. Useful in applications that involve data structures like linked list
and trees.

Department of Computer Science, RLJIT 35


Unions
Union is a user-defined data type in C, which is used to store collection of
dissimilar data items (just like a structure).
Union and Structures are same except allocating memory for their members.
Structure allocates storage space for all its members separately, whereas unions
allocates one common storage space for all its members.
Structure declaration: Example:
Syntax : union student
union tagname {
{ char name[20];
int age;
type1 var1;
int rlno;
type2 var2; };
..............................
typeN varN; Note: here, union allocates only 20 bytes of memory,
}; since the name field or mrmber
Requires the maximum space compared to age and rlno.
Declaration of union variables:
union tagname var1, var2, ……,var N;
Example:
union student s1,s2,s3; Department of Computer Science, RLJIT 36
Unions

Department of Computer Science, RLJIT 37


Pointers
Pointer is a variable that stores/points the address of another variable.
Pointer Declaration:
Syntax :
data_type *var_name;
Example:
int *p; // p is pointer which can hold the address of integer variable.
char *q; // q is pointer which can hold the address of character
variable.

To assign address of variable to pointer we need follow the 4 steps


Step 1: Declare a data variable. int a=10;
Step 2: Declare a pointer variable. int *p;
Step 3: Assign address of data variable to pointer p=&a
Step 4: Access the pointer printf(“value of a is %d”, *p)

Department of Computer Science, RLJIT 38


#include <stdio.h>

int main( )
Output
{ value of a = 5
int a = 5;
int *b; value of a = 5
b = &a;

printf ("value of a = %d\n", a);


printf ("value of a = %d\n", *(&a));
return 0;
}
Pointers
Advantages of Pointers:
• Pointers provide direct access to memory
• Pointers provide a way to return more than one value to the functions
• Reduces the storage space and complexity of the program
• Reduces the execution time of the program
• Provides an alternate way to access array elements
• Pointers can be used to pass information back and forth between the
calling function and called function.
• Pointers allow us to perform dynamic memory allocation and
deallocation.
• Pointers helps us to build complex data structures like linked list,
stack, queues, trees, graphs etc.

Department of Computer Science, RLJIT 40


Pointers
Disadvantages of Pointers:
• Uninitialized pointers might cause segmentation fault.

• Dynamically allocated block needs to be freed


explicitly. Otherwise, it would lead to memory leak.

• Pointers are slower than normal variables.

• If pointers are updated with incorrect values, it might lead to


memory corruption.

Department of Computer Science, RLJIT 41


Dynamic memory allocation
Memory management is important task in computer programming.
There are two types of memory management.
1. Static memory management: The allocation and deallocation of
memory is done during compilation time of the program.
Example: int a[10];
2. Dynamic memory management: The process of allocating
memory during program execution(run time) is called
dynamic memory allocation.

C language offers 4 dynamic memory allocation functions. They


are,
malloc() calloc() realloc() and free()

Department of Computer Science, RLJIT 42


Dynamic memory allocation
Static memory allocation Dynamic memory allocation
Memory allocation is performed Memory allocation is performed
at compile time. at run time.

Prior to allocation, fixed size of No need to know the size of


memory has to be decided. memory prior to allocation.
Wastage or shortage of memory Memory is allocated as per
occurs. requirement.
Example: arrays Example: linked list

Department of Computer Science, RLJIT 43


Dynamic memory allocation
malloc ( ) function:
It allocates block of memory during run time.
The size of the block is the number of bytes specified in the
parameter (i.e. size).
Syntax:
ptr= (data type *) malloc(size);

It allocates a block of memory which is specified in parameter size.


This function returns the staring address of allocated memory on
successful allocation.
This function returns NULL on unsuccessful allocation.( if specified
memory is not available)
Example:
ptr= (int *) malloc(10);
In above example, malloc function allocates 10 bytes of memory and
returns the starting address toDepartment
the pointer ptr. RLJIT
of Computer Science, 44
Dynamic memory allocation
calloc () function:
It allocates multiple block of memory during run time.
calloc means contiguous allocation of memory.
Syntax:
ptr= (data type *) calloc(n, size);
Where, n is number of blocks to be allocated. size is size of each
block.
Totally it allocates ( n * size) bytes of memory
This function returns the staring address of allocated memory on
successful allocation.
This function returns NULL on unsuccessful allocation.( if specified
memory is not available)
Example:
ptr= (int *) calloc(10 , sizeof(int));
In above example, calloc function allocates 20 bytes of memory and
returns the starting address toDepartment
the pointer ptr. RLJIT
of Computer Science, 45
Dynamic memory allocation
Difference between malloc() and calloc() functions in C

Department of Computer Science, RLJIT 46


Dynamic memory allocation
realloc () function:
realloc means reallocation of memory.
Process of allocating or deallocating a memory for already allocated
memory during run time is called reallocation of memory.
Syntax:
ptr= (data type *) realloc(ptr, newsize);
The realloc() function accepts two arguments,
The first argument ptr is a pointer to the first byte of memory that
was previously allocated using malloc() or calloc() function.
The second argument newsize parameter specifies the new size of
the block in bytes.

Department of Computer Science, RLJIT 47


Example
ptr= (int *) malloc(50);
This first line allocated 50 bytes of memory
and return starting address to the pointer ptr.

ptr= (int *) realloc(ptr,100);


This line reallocated the memory from 50
bytes to 100 bytes and return starting address
to the pointer ptr.
Dynamic memory allocation
free () function:
This function is used to deallocate (or free) the allocated memory.
Syntax:
free(ptr);
This function free deallocates the memory which is pointed by the
pointer ptr.
Example
ptr= (int *) malloc(50); This line allocated 50 bytes of memory
and return starting address to the
pointer ptr.

free(ptr); deallocate the memory which is


ptr=NULL; allocated for pointer ptr, and finally
assign NULL to pointer ptr.
Department of Computer Science, RLJIT 49
Representation of Linear Arrays in Memory
Representation of 1-D Array:
In C language, array index always starts from 0 (zero).
Below figure shows, the representation of 1-D array ( Assuming the
starting address 200).

Formula to find the location a[index];


Loc A[index] = BaseAddress[A]+ w*(index-LB)
Where, w is word length(size of each element)
LB is Lower Bound of array.
Formula to find the Number of Elements in an 1D Array:
Number of elements = UB – LB + 1
Where, UB is Upper Bound and LBofisComputer
Department Lower Bound
Science, RLJIT 50
Representation of Linear Arrays in Memory
Problem:
Consider linear array AAA(5:50) and BBB(-5:10)
a) Find the number of elements.
Solution: AAA(5:50)
Number of elements = UB – LB + 1
Number of elements = 50-5+ 1=46

BBB(-5:10)
Number of elements = UB – LB + 1
Number of elements = 10-(-5)+ 1=10+5+1=16

b) Suppose Base (AAA) is 300 and w=2. Find AAA[15] .


Solution:
Loc AAA[index] = BaseAddress[AAA]+ w*(index-LB)
Loc AAA[15] = 300+ 2*(15-0)=330
Department of Computer Science, RLJIT 51
Dynamically allocated arrays
The array can be dynamically allocated using malloc( ), calloc( ) or
realloc( ) function.
Similarly allocated memory can be freed.

Advantage: Memory for array of any desired size can be allocated.


No need of fixed sized array.

Department of Computer Science, RLJIT 52


Dynamically allocated arrays
C Program using Dynamic array to add n array elements.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,sum=0;
int *a;
printf(“enter the number of elements\n”);
scanf(“%d”, &n);
a=(int *) malloc (n*sizeof(int));
if(a==NULL)
printf(“ No Memory Allocation\n”);
printf(“ Enter the Array Elements\n”);
for(i=0; i<n; ++i)
{
scanf(“%d”, a+i);
sum=sum+(*(a+i));
}
printf(“ Sum = %d\n”, sum);
free(a);
getch(); Department of Computer Science, RLJIT 53
}
Array operations

Traversal - This operation is used to print the elements of


the array.

Insertion - It is used to add an element at a particular


index.

Deletion - It is used to delete an element from a particular


index.

Search - It is used to search an element using the given


index or by the value.

Update - It updates an element at a particular index.


Array Operations
Traversing:
Traversal of a data structure means processing all the data elements
present in it i.e. process every element of data structure is visited once
and only once, such type of operation is called as traversing.

For example to display all the elements of an array, every element is


visited only once, so it is called as traversing operation.
Function to display n elements of array (Traversing an array) as shown below.

void display(int a[ ], int n )


{
int i;
printf("The array elements are:\n");
for(i=0; i<n; i++)
printf("%d\t", a[i]);
} Department of Computer Science, RLJIT 55
Array Operations
Insertion:
Insertion means addition of a new data element in a data structure.

When an element of the same type is added to an existing data


structure, the operation is called as Insertion operation.
Function to inserting an item into an array based on position as shown below.
int insert(int a[ ], int n, int pos, int item)
{
int i;
if(pos>n || pos<0)
{
printf(“ Invalid Position\n”);
return n;
}
for(i=n-1; i>=pos-1; i--)
{
a[i+1] = a[i];
}
a[pos-1] = item;
return n+1; Department of Computer Science, RLJIT 56
}
Array Operations
Deletion:
Deletion means removal of a data element from a data structure if it is
found. When an element is removed from the data structure, the
operation is called as Deletion operation.
Function to delete an item into an array based on position as shown below.
void del(int a[ ],int n, int pos )
{
int i;
if(pos>n || pos<0)
{
printf(“ Invalid Position\n”);
return n;
}
printf(“item deleted = %d\n”, a[pos]);
for(i=pos-1; i<n-1; i++)
{
a[i] = a[i+1];
}

return n-1; Department of Computer Science, RLJIT 57


} refer----> https://www.log2base2.com/data-structures/array/remove-a-specific-element-from-array.html
Array Operations
Searching:
Searching involves searching for the specified data element in a data
structure.
When an element is checked for its presence in a data structure, that
operation is called as “searching‟ operation.
The element that is to be searched is called as key element.
The searching can be done using either “linear search‟ or “binary
search‟.

Department of Computer Science, RLJIT 58


Array Operations
Linear Search:
Linear searching is also called sequential search.
In this technique, we search for given key in the array in linear order
one after the other from first element to last element.
If key present, we say search successful and return the location
(position), Otherwise search is unsuccessful.
Simple logic of Linear Search: c-function Linear Search:
Step 1 - Compare the key element with the first
element in the Array. int linear_search( int A[ ], int n, int
Step 2 - If both are matched, then return position key )
(search successful) {
Step 3 - If both are not matched, then compare for(i = 0; i < n; i++)
key element with the next element in the {
Array. if(A[ i ] ==key )
Step 4 - Repeat steps 3 and 4 until last return pos;
element. }
Step 5 - return -1, unsuccessful. return -1;
Department of Computer Science, RLJIT 59
}
Example :
Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170},
Input-x = 110;
Output: 6
Explanation: Element x is present at index 6
Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170},
Input -> x = 175;
Output: -1
Explanation: Element x is not present in arr[].

Follow the below idea to solve the problem:


Iterate from 0 to N-1 and compare the value of every index with x if they match
return index
Follow the given steps to solve the problem:
1. Start from the leftmost element of arr[] and one by one compare x with
each element of arr[]
2. If x matches with an element, return the index.
3. If x doesn’t match with any of the elements, return -1.
Array Operations
Binary Search:
 We always get a sorted list before doing the binary search. Now
suppose we have an ascending order record.
 At the time of search it takes the middle record/element, if the
searching element is greater than middle element then the element
mush be located in the second part else it is in the first half.
 In this way this search algorithm divides the records in to two parts
in each iteration and thus called binary search.
 In binary search, we first compare the key with the item in the
middle position of the array. If there's a match, we can return
immediately. If the key is less than the middle key, then the item
must lie in the lower half of the array; if it's greater than the item
must lie in the upper half of the array. So we repeat the procedure
on the lower or upper half of the array depending on the
comparison.
Department of Computer Science, RLJIT 61
Array Operations
c-function Binary Search:
int binary_search( int a[ ], int n, int key )
{
int low,high,mid;
low=0;
high=n-1;

while( low<=high)
{
mid=(low+high)/2;
if (key == a[mid])
return mid;
if (key < a[mid])
high=mid-1;
if (key > a[mid])
low=mid+1;
}
return -1;
} Department of Computer Science, RLJIT 62
Array Operations
Sorting:
 Arranging data elements of a data structure in a specified order is
called sorting.
 When all the elements of array are arranged in either ascending or
descending order, the operation is called as Sorting.
 The Sorting can be done using Insertion, Selection or Bubble sort
techniques.
Consider the unsorted elements as shown below

After sorting them in ascending order, we get the following list.

After sorting them in descending order, we get the following list.

Department of Computer Science, RLJIT 64


Array Operations
Bubble sort:
This sorting algorithm is comparison based algorithm in which each
pair of adjacent elements is compared and elements are swapped if
they are not in order.
Simple logic of Bubble sort:
Given an array of n items
1. Compare pair of adjacent items
2. Swap if the items are out of order
3. Repeat until the end of array
The largest item will be at the last position
4. Reduce n by 1 (i.e n=n-1) and go to Step 1

Note:
• In bubble sort we perform n-1 passes.
• In each pass one element will be placed in correct position.

Department of Computer Science, RLJIT 65


Working of Bubble Sort
Suppose we are trying to sort the elements in ascending order.
1. First Iteration (Compare and Swap)
1. Starting from the first index, compare the first and the
second elements.

2. If the first element is greater than the second element, they


are swapped.

3. Now, compare the second and the third elements. Swap


them if they are not in order.

4. The above process goes on until the last element


Bubble sort example
This algorithm could be used to sort the following list:
3, 2, 4, 1, 5
The first loop of the algorithm would produce:
3, 2, 4, 1, 5 (2<3 so the two values are swapped)
2, 3, 4, 1, 5 (3<4 so the two values are not swapped)
2, 3, 4, 1, 5 (1<4 so the two values are swapped)
2, 3, 1, 4, 5 (4<5 so the two values are not swapped)
2, 3, 1, 4, 5 (First pass completed)

2, 3, 1, 4, 5 (2<3 so the values are not swapped)


2, 3, 1, 4, 5 (1<3 so the values are swapped)
2, 1, 3, 4, 5 (3<4 so the values are not swapped)
2, 1, 3, 4, 5 (4<5 so the values are not swapped)
2, 1, 3, 4, 5 (Second pass completed)

2, 1, 3, 4, 5 (1<2 so the values are swapped)


1, 2, 3, 4, 5 (2<3 so the values are not swapped)
1, 2, 3, 4, 5 (3<4 so the values are not swapped)
1, 2, 3, 4, 5 (4<5 so the values are not swapped)
1, 2, 3, 4, 5 (Third pass completed)
Array Operations
Function:
void bubble_sort( int A[ ], int n )
{
int temp,i,j;
for(j = 0; j< n-1; j++)
{
for(i = 0; i < n-j-1; i++)
{

if(A[ i ] > A[ i+1] )


{

temp = A[ i ];
A[ i ] = A[ i+1 ];
A[ i + 1] = temp;

}
}
} Department of Computer Science, RLJIT 68
}
Array Operations
Polynomial:
 A polynomial is mathematical expression consisting of sum of
terms. A term is made up of coefficient and exponent.
 An example of polynomial is

Representation of Polynomial using Array

Department of Computer Science, RLJIT 69


Array Operations
Below figure show how two polynomials are stored in array.
Polynomial is stored one after the other in memory location.

Department of Computer Science, RLJIT 70


Array Operations
Representation of Addition of Polynomial using Array
• Consider the two polynomial as shown below A & B, and below
diagram represent the addition of two polynomials

A(x) = 100x4 +70x3 +55x +20

B(x) = 90x5 +40x4 +35x3 +50x2 +33

Department of Computer Science, RLJIT 71


Array Operations
• Representation of Polynomial using Structure
Each term of polynomial contain two things. -
– Coefficient.
– Power of Exponential
• Following structure declaration is used to represent a term of
polynomial.
typedef struct
{
int cf ;
int px ;
}poly;
Consider the following declaration
poly p[10];
Department of Computer Science, RLJIT 72
using this we can read 10 terms of polynomial.
Array Operations
void display_poly( poly p[ ],int n)
Program to read and print the polynomial
{
typedef struct
printf(“%dx^%d”,p[0].cf,p[0]px);
{
int cf ;
for(i=1;i<n;i++)
int px ;
{
}poly;
printf(“+%dx^%d”,p[i].cf,p[i]px);
void read_poly( poly p[ ],int n)
}
{
}
int cf,px;
void main( )
for(i=0;i<n;i++)
{
{
poly p[ ];
printf(“enter cof and pox\n”):
int n;
scanf(“%d%d”,cf,px);
printf(“Enter the no of terms \n”);
p[i].cf=cf;
scanf(“%d”,&n);
p[i].px=px;
read_poly( p,n);
}
display_poly( p, n);
Department of Computer Science, RLJIT
} 73
}
What is a matrix?
•A matrix can be defined as a two-dimensional array having 'm'
rows and 'n' columns.
• A matrix with m rows and n columns is called m × n matrix.

What is a sparse matrix?


•Sparse matrices are those matrices that have the majority of their
elements equal to zero.

•In other words, the sparse matrix can be defined as the matrix that
has a greater number of zero elements than the non-zero elements.
Array Operations
Sparse Matrix :
A matrix that has very few non-zero elements (or A matrix that has
more number of zero elements)

Sparse Matrix Representation


• A sparse matrix can be represented by using TWO representations,
those are as follows...

• Triplet Representation.(Array Representation)


• Linked Representation.
Department of Computer Science, RLJIT 75
Array Operations
1.Triplet/ Array Representation:
• In this representation, we consider only non-zero values along with
their row and column index values.
• In this representation, the 0th row stores
– total number of rows,
– total number of columns and
– total number of non-zero values in the sparse matrix

Department of Computer Science, RLJIT 76


Array Operations
Triplet Representation (Array Representation)
As each non-zero value of sparse matrix can be defined using triples
<row,col,val>.
Sparse matrix can be created using the Array of triples as shown
below.

typedef struct
{
int row ;
int col ;
int val;
}term;

term a[5]; // using this weDepartment


can store 5 non-zero
of Computer Science, RLJIT values.
77
Array Operations
Function to read sparse matric
void read(term a[ ])
{
printf(“enter no of non-zero values\n”):
sacnf(”%d”,&n);
for(i=0;i<=n;i++)
{
printf(“ enter row col and value\n”);
scanf(“%d”,a[i].row);
scanf(“%d”,a[i].col);
scanf(“%d”,a[i].val);
}
}
Department of Computer Science, RLJIT 78
Example C- Program for sparse matrix

#include <stdio.h> if (counter > ((m * n) / 2))


{
void main () printf("The given matrix is sparse matrix \n");
{ }
static int array[10][10]; else
int i, j, m, n; printf("The given matrix is not a sparse matrix \n");
int counter = 0; printf("There are %d number of zeros", counter);
}
printf("Enter the order of the matix \n");
printf("Enter the number of rows in array: ");
scanf("%d", &m);
printf("Enter the number of columns in array: ");
scanf("%d", &n);

printf("Enter the co-efficients of the matix: \n");


for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
if (array[i][j] == 0)
{
++counter;
}
}
}
Array Operations
Transpose of sparse Matrix
Transpose of sparse matrix can be obtained by changing row elements
into column elements and vice versa.
Ex: Represent the following sparse matrix using triples in a single
dimensional array? Also show the transpose of the given matrix
represented as a triple.

Department of Computer Science, RLJIT 80


Array Operations

Department of Computer Science, RLJIT 81


Array Operations
Function to find the transpose of a given sparse matrix

Department of Computer Science, RLJIT 82


Questions???
1. Define Data structure. Give its classification. What are the basic operations
that can be performed on data structure?
2. Define array and its types & explain how array is declared & accessed with
an example.
3. What is structure? How is it different from array? Explain different types of
structure declaration with example and give the difference between
structure and union.
4. Brief about Self Referential Structure.
5. Define Pointers. How to declare and initialize pointers, Explain with
example and give advantage and disadvantages of pointer.
6. Explain dynamic memory allocation functions in detail.
7. List the difference between Static memory allocation and Dynamic memory
allocation.
8. Briefly explain dynamically allocated arrays with example.
9. In brief explain array operations of data structures.

Department of Computer Science, RLJIT 83

You might also like