0% found this document useful (0 votes)
17 views

1.3.2 Searching Operation On Array

Uploaded by

tifiba1487
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

1.3.2 Searching Operation On Array

Uploaded by

tifiba1487
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIVERSITY INSTITUTE OF COMPUTING

Bachelor of Computer Application


Subject Name: Data Structure
23CAT-201/ 23SCT-201
VISION

To be a Centre of Excellence for nurturing computer professionals with


strong application expertise through experiential learning and research
for matching the requirements of industry and society instilling in them
the spirit of innovation and entrepreneurship.

2
Mission of the Department

M1. To provide innovative learning centric facilities and quality-


oriented teaching learning process for solving computational problems.
M2. To provide a frame work through Project Based Learning to
support society and industry in promoting a multidisciplinary activity.
M3. To develop crystal clear evaluation system and experiential
learning mechanism aligned with futuristic technologies and industry.
M4. To provide doorway for promoting research, innovation and
entrepreneurship skills incollaboration with industry and academia.
M5. To undertake societal activities for upliftment of rural/deprived
sections of the society.
3
Program Outcomes
• PO1 Apply mathematics and computing fundamental and domain concepts to find out the solution of defined problems and requirements. (Computational
Knowledge)
• PO2 Use fundamental principle of Mathematics and Computing to identify, formulate research literature for solving complex problems, reaching appropriate
solutions. (Problem Analysis)
• PO3 Understand to design, analyze and develop solutions and evaluate system components or processes to meet specific need for local, regional and global public
health, societal, cultural, and environmental systems.
• PO4 (Design /Development of Solutions)Use expertise research-based knowledge and methods including skills for analysis and development of information to
reach valid conclusions. (Conduct Investigations of Complex Computing Problems)
• PO5 Adapt, apply appropriate modern computing tools and techniques to solve computing activities keeping in view the limitations. (Modern Tool Usage)
• PO6 Exhibiting ethics for regulations, responsibilities and norms in professional computing practices. (Professional Ethics)
• PO7 Enlighten knowledge to enhance understanding and building research, strategies in independent learning for continual development as computer applications
professional. (Life-long Learning)
• PO8 Establishing strategies in developing and implementing ideas in multi- disciplinary environments using computing and management skills as a member or
leader in a team. (Project Management and Finance)
• PO9 Contribute to progressive community and society in comprehending computing activities by writing effective reports, designing documentation, making
effective presentation, and understand instructions. (Communication Efficacy)
• PO10 Apply mathematics and computing knowledge to access and solve issues relating to health, safety, societal, environmental, legal, and cultural issues within
local, regional and global context. (Societal and Environmental Concern)
• PO11 Gain confidence for self and continuous learning to improve knowledge and competence as a member or leader of a team. (Individual and Teamwork)
• PO12 Learn to innovate, design and develop solutions for solving real life business problems and addressing business development issues with a passion for quality
competency and holistic approach. (Innovation and Entrepreneurship)

4
Program Educational Objectives

PEO1 Demonstrate analytical and design skills including the ability to generate creative solutions and foster
team-oriented professionalism through effective communication in their careers.
PEO2 Expertise in successful careers based on their understanding of formal and practical methods of
application development using the concept of computer programming languages and design principles in
accordance to industry 4.0
PEO3 Exhibit the growth of the nation and society by implementing and acquiring knowledge of upliftment of
health, safety and other societal issues.
PEO4 Implement their exhibiting critical thinking and problem- solving skills in professional practices or tackle
social, technical and business challenges.

5
Program Specific Outcomes

PSO1 Analyze their abilities in systematic planning, developing, testing


and executing complex computing applications in field of Social-Media
and Analytics, Web Application Development and Data Interpretations.
PSO2 Apprise in-depth expertise and sustainable learning that
contributes to multi-disciplinary creativity, permutation, modernization
and study to address global interest.

6
Topic To be Covered

• Linear Search (CO2)


• Binary Search (Iterative approach)(CO2)
• Binary Search (Recursive approach)(CO2)
Array - Search Operation

• Search is the process of finding a specific element within an array.


• This is done by comparing the target element with each element in
the array until a match is found.
• There are various search algorithms that can be used, such as linear
search and binary search.
• There are several searching algorithms. The most commonly used
among them are:
• Linear Search
• Binary Search
Linear Search:
• Linear Search is defined as a sequential search algorithm that starts at
one end and goes through each element of a list until the desired
element or group of elements is found. Otherwise, the search
continues till the end of the data set. This has a time complexity
of O( N) where ‘N’ is the length of the array
• Algorithm:
1. Start
2. for i=0 to size-1 do
3. if array[i]==Key then
4. Return i
5. else Print "elemnt not exist in array"
6. Stop
For example: Consider the array arr[] = {10, 50,
30, 70, 80, 20, 90, 40} and key = 30

Step 1: Start from the first element (index 0) and compare key with each element (arr[i]).

Comparing key with first element arr[0]. SInce not equal, Comparing key with next element arr[1]. SInce not equal,
the iterator moves to the next element as a potential the iterator moves to the next element as a potential
match. match.

Step 2: Now when comparing arr[2] with key, the value matches. So the Linear Search Algorithm will yield a
successful message and return the index of the element when key is found (here 2).
Code:
// Linear Search in C++ int main()
{
#include <iostream>
int array[] = {2, 4, 0, 1, 9};
using namespace std; int x = 1;
int search(int array[], int n, int x) int n = sizeof(array) / sizeof(array[0]);
{ int result = search(array, n, x);
// Going through array if (result == -1)
sequencially {

for (int i = 0; i < n; i++) cout << "Element not found";


}
if (array[i] == x)
else
return i; {
return -1; cout << "Element found at index: " <<
} result;
}}
Time Complexity

• Average: O( n)
• Best: O(1)
• Worst: O( n)
The average time complexity is O( n) as the element to be found may
be present at the end of the list or may not be present at all. Linear
search has to visit all the elements until the needed element is found.
Algorithmically, this comes out to be O( n).
The best and worst case of a search algorithm will be O(1) and O( n)
respectively, as the element to be searched could always be found on
the first iteration or the last iteration.
Binary Search:
• Binary Search Algorithm is a searching algorithm
used in a sorted array by repeatedly dividing
the search interval in half.
• The linear search approach has one
disadvantage. Finding elements in a large array
will be time consuming. As the array grows, the
time will increase linearly. A binary search can be
used as a solution to this problem in some cases.
• The principle of binary search is how we find a
page in book. We open the book at a random
page in the middle and based on that page we
narrow our search to the left or right of the
book. Indeed, this only is possible if the page
numbers are in order.
Recursive Binary Search
Algorithm:
• Create a recursive function and compare the mid of the search space with the key. And based on
the result either return the index where the key is found or call the recursive function for the next
search space

• Algorithm:
BinarySearch(array, start, end , key)
1. Start
2.if start<=end then
mid=start+(end-start)/2
3. if array[mid]==key then
return mid location
4. else if array[mid]<key then
call BinarySerach(array, mid+1, end, key)
5. else when array[mid]>key then
call BinarySerach(array, start, mid-1, key)
6. else
return invalid location
7. Stop
How to calculate “mid” or Middle Element
Index in Binary Search?

• The most common method to calculate mid or middle element


index in Binary Search Algorithm is to find the middle of the highest
index and lowest index of the searchable space, using the formula mid
= low + \frac{(high – low)}{2}

Finding the middle index “mid” in Binary Search Algorithm


How does Binary Search Algorithm work?
Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, and the target = 23.

First Step: Calculate the mid and compare the mid element with the key. If the key is less than mid
element, move to left and if it is greater than the mid then move search space to the right.

Key (i.e., 23) is greater than current mid element (i.e., 16). Key is less than the current mid 56. The search space moves
The search space moves to the right. to the left.

Second Step: If the key matches the value of the mid element, the element is found and stop search.
Code: (Implementation of Recursive Binary Search Algorithm)

#include <bits/stdc++.h> // Driver code


using namespace std; int main()
// A recursive binary search function. It returns location of x in given {
array arr[start..end] is present, otherwise -1
int arr[] = { 2, 3, 4, 10, 40 };
int binarySearch(int arr[], int start, int end, int key)
int key = 10;
{
int n = sizeof(arr) / sizeof(arr[0]);
if (start >= end) {
int result = binarySearch(arr, 0, n - 1, key);
int mid = start + (end - start) / 2; // If the element is present at
the middle itself if(result == -1)

if (arr[mid] == key) {

return mid; cout << "Element is not present in array";


}
if (arr[mid] > key) // If element is smaller than mid, then it can
only be present in left subarray else

return binarySearch(arr, start, mid - 1, key); {

// Else the element can only be present in right subarray cout << "Element is present at index " << result;

return binarySearch(arr, mid + 1, end, key); }

} return 0;

} }
Complexity

• Time Complexity:
• Best Case: O(1)
• Average Case: O(log N)
• Worst Case: O(log N)
• Auxiliary Space: O(1), If the recursive call stack is considered then the
auxiliary space will be O(logN).
Iterative Binary Search
Algorithm:

• Here we use a while loop to continue the process of comparing the key and splitting the
search space in two halves.

• Algorithm:
1. Start
2. Set start=LB and end=UB, mid=int((start+end)/2)
3. Repeat step 4 to 8 while start<=end and A[mid]!=key
4.if key<=A[mid] then
set end=mid-1
5. else
set start=mid+1
6. set mid=int((start+end)/2)
7. if A[mid]==key
set loc=mid
8. else
set loc=Null
9. Stop
Code: (Implementation of Iterative
Binary Search Algorithm:)
// An iterative binary search function. // Driver code
int binarySearch(int arr[], int start, int end, int key) int main(void)
{ {
while (start <= end) { int arr[] = { 2, 3, 4, 10, 40 };
int mid = start + (end - start) / 2; int key = 10;
// Check if x is present at mid int n = sizeof(arr) / sizeof(arr[0]);
if (arr[mid] == key) int result = binarySearch(arr, 0, n - 1, key);
return mid; if(result == -1)
// If key greater, ignore left half
{
if (arr[mid] < key)
start = mid + 1; cout << "Element is not present in array";
// If key is smaller, ignore right half }
else else
end = mid - 1;
} {
// If we reach here, then element was not present cout << "Element is present at index " << result;
return -1; }
} return 0;
}
Complexity

• Time Complexity: O(log N)


• Auxiliary Space: O(1)
Book References
TEXT BOOKS
• Seymour Lipchitz, Schaum's Outlines Series Data Structures TMH. J.P. Hayes,
Computer Organization and Architecture, Third Edition, TMH.
• Data Structure Theory Problem and Algorithms, R.S. Salaria, Khanna Book
Publishing Company, Delhi.
REFERENCE BOOKS
• Introduction to Data Structures Applications, Trembley&Soreson, Second
Edition, Pearson Education Robert L. Britton, MIPS Assembly Language
Programming, Pearson Prentice Hall.
• A. Tanenbaum, Y. Lanhgsam and A. J. Augenstein, Data Structures Using C++,
Prentice Hall of India, 1990
Video Links

https://www.youtube.com/watch?v=C46QfTjVCNU
THANK YOU

Created by: Deepika Dhiman (E15896)


[email protected]

You might also like