0% found this document useful (0 votes)
176 views31 pages

Searching and Sorting in Arrays

In computer science, a data structure is a data organization, management, and storage format that enables efficient access and modification. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data

Uploaded by

AR123456
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)
176 views31 pages

Searching and Sorting in Arrays

In computer science, a data structure is a data organization, management, and storage format that enables efficient access and modification. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data

Uploaded by

AR123456
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

Data Structures

Data Structure Lecture No 4


Searching and Sorting in Array
Data Structures

In This Lecture Topics Covered

 Searching
 Linear Search
 Binary Search
 Sorting
 Bubble Sort
 Selection Sort
 Insertion Sort
Data Structures

Searching
 Important area in Computer Science

 The Process of finding particular element in an


array is called searching

 The Technique we use for searching an element


from the array is called Linear Search

 The element which is searched is sometimes


called the Key Element
Data Structures

Linear Search or Sequential Search


 This is Very Simple Algorithm

 It uses a loop to sequentially step through an


array , starting with the first element.

 It Compares each element with the value being


searched for and stops when that value is found
or the end of the array is reached.
Data Structures

Linear Search or Sequential Search


 Linear Search or Sequential Search is one of the
Searching Algorithm in which we have some
data in a data structure like array data structure
and we have to search a particular element in it
which is known as key.
 By traversing the whole data structure
elements from start to end one by one to find
the key comparing with each other structure
element the key.

Data Structures

Linear Search or Sequential Search


 There can be two possible outcomes if we are
assuming that data structure like array contains
unique values.

 Linear Search Key Found


 Linear Search failed
Data Structures

Linear Search or Sequential Search


0 1 2 3 4 0 1 2 3 4

5 3 17 60 2 5 3 17 60 2

Key Key
0 1 2 3 4 0 1 2 3 4
5 3 17 60 2 5 3 17 60 2

0 1 2 3 4

Key 5 3 17 60 2 Key

Key
Data Structures

Linear Search or Sequential Search


 For Example An Array is
int array[8] = {6 4 1 97 3 2 8}
 If we have to find the 3 how we find using the
Linear Search?
 Compare 3 with each element of the array
 if it match with any element of the array then it
returns its index.
 Otherwise No is Not found in the array
Data Structures

Linear Search or Sequential Search


Key List
3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8
Data Structures

Linear Search or Sequential Search


#include<iostream.h>
Using namespace std;
int main(){
cout<<“Enter the size of Array”;
int size;
cin>>size;
int array[size] , key , i;
for(int j = 0;j<size;j++){
cout<<“Enter”<<j<<“Elements”;
cin>>array[j];
}
Data Structures

Linear Search or Sequential Search


for(int a = 0; a<size;a++){
cout<<“Array[”<<a<<“] is =”;
cout<<array[a];
}
Cout<<“Enter Key to Search in the Array”;
Cin>>key;
for(i = 0; i<size;i++){
if(key = array[i])
cout<<“Key Found at Index No”<<i<<endl;
Break;
}
}
Data Structures

Linear Search or Sequential Search


If(i!=size){
cout<<“Key Found at index”<<i<<endl;
}
else{
cout<<“Key Not Found”<<endl;
}
return 0;
}
Data Structures

Linear Search or Sequential Search


If(i!=size){
cout<<“Key Found at index”<<i<<endl;
}
else{
cout<<“Key Not Found”<<endl;
}
return 0;
}
Data Structures

Analysis & Conclusion


Worst Case: The Worst Case for Linear Search is that
if the element to be searched is not found in the
list. This traverse the entire array and return
nothing. Worst case running time is O(n)
Average Case: The Running Time of Average case is
also O(n)
Best Case: The Best case can be reached if the
element to be found is the first one in the list. So
the time is constant O(1)
Data Structures

Efficiency of the Linear Search

 The Advantage is its Simplicity


 it is easy to understand
 Easy to Implement
 Does Not required the array in order

The Disadvantages
if there are 20,000 items in the array and what
you are looking for is in the 19,999th element we
need to search through the entire list.
Data Structures

Binary Search Algorithm


 Following C++ Program first ask to the user to
enter how many elements he want to store in the
array then ask to enter the [Link]
storing the elements in the array program ask to
the user to enter the element which he wan to
search in the array wheter that no is present or
not. The Searching Technique is Binary Search.
Data Structures

Binary Search Algorithm


#inlcude<iostream>
using namespace std;
int main(){
int n , i , arr[50] , search , first , last , middle;
cout<<“Enter Total No of Elements”<<endl;
cin>>n;
cout<<“Enter”<<n<<“No”<<endl;
for(i = 0; i<n;i++){
cin>>arr[i];
cout<<“Enter a no to find”<<endl;
cin>>search;
}
Data Structures

Binary Search Algorithm


first = 0;
last = n-1;
middle = (first + last)/2;
while(first <= last){
if(arr[middle]<search){
first = middle + 1;
}
else if(arr[middle] == search){
cout<<search<<“Found at location”<<endl;
}
}
}
Data Structures

Sorting in Array
 Arrangement of Data in the array is called
sorting.

 We Can Sort data in ascending or Descending.

 Lot of Techniques or algorithms are used to sort


the data in array

 First Technique which is used is called bubble


sort.
Data Structures

Sorting in Array
 Bubble Sort is sorting tecnique in which each pair
of adjacent elements are compared if they are in
wrong order we swap them.

 The Process is carry on until the whole array is


sorted.

 This algorithms is named as bubble sort because


same as like bubbles the smaller or lighter
elements comes up (at start) and bigger or havier
element goes down (at end).
Data Structures

Bubble Sort
0 1 2 3 4

3 1 15 57 9

Decsending 57 15 9 3 1

Ascending 1 3 9 15 57
Data Structures

Bubble Sort

Array 2 1 3 4 5

Array 2 1 3 4 5
Data Structures

Bubble Sort

Array 2 1 3 4 5

Array 2 1 3 4 5

2 3 1 4 5
Data Structures

Bubble Sort

Array 2 1 3 4 5

Array 2 1 3 4 5

2 3 1 4 5

2 3 4 1 5
Data Structures

Bubble Sort

Array 2 1 3 4 5

Array 2 1 3 4 5

2 3 1 4 5

2 3 4 1 5

2 3 4 5 1
Data Structures

Binary Search Algorithm


#inlcude<iostream>
using namespace std;
Void bubblesort(int number[] , int size);
int main(){
int size , number[size];
cout<<“Enter the size of array”<<endl;
cin>>size;
cout<<“Enter”<<n<<“No”<<endl;
for(i = 0; i<size; i++){
cin>>number[i];
bubblesort(number , size);
}
Data Structures

Binary Search Algorithm


Void bubblesort(number[] , size){
cout<<“Sorted Array”<<endl;
for(int I = 0;i<size-1;i++){
for(int j = 0;j<size-1;j++){
if(number[j] < number[j+1]){
int temp = number[j];
number[j] = number[j+1];
number[j+1] = temp;
}
}
}
}
}
Data Structures

Explaination of Code
 Now this program will be explained with proper
example.
 Just Consider the array entered by the user.

10 40 13 20 8
 Now the program will use the nested loop to
perform sorting. The iterations of outer loop will
specified the number of passes and the inner
loop will specify the number of iterations.
Data Structures

Explaination of Code
 At the beginning when the loop begins, the
value of i = 0 , Therefore first pass is started.
 Just Consider the array entered by the user.

10 40 13 20 8
In the first pass the value of i = 0 and the inner loop
came into action it will perform 4 iteration and
check the condition of the following block of
statement.
Data Structures

Explaination of Code
Iteration No 1:-

10 40 13 20 8
At first Iteration the value of j =0 and the value of
j = j+1 , Therefore it will compare the values of zero
index and the first index of an array. As we can see
that the value at zero index is smaller than first
index therefore array remains same.
Data Structures

Explaination of Code
Iteration No 1:-

10 40 13 20 8
At first Iteration the value of j =0 and the value of
j = j+1 , Therefore it will compare the values of zero
index and the first index of an array. As we can see
that the value at zero index is smaller than first
index therefore array remains same.

Common questions

Powered by AI

Linear Search is straightforward and does not require the array to be sorted, making it easy to implement . However, its main disadvantage is inefficiency with O(n) time complexity in both average and worst cases, especially with large datasets . Binary Search requires the array to be pre-sorted, but it is far more efficient with a time complexity of O(log n) in the average and worst cases due to its divide-and-conquer strategy . The main disadvantage of Binary Search is the prerequisite sorting of the array, which may add additional computational overhead .

Binary Search employs divide-and-conquer principles by repeatedly dividing the search interval in half. Starting with the middle element, it checks whether the target element equals this middle value. If not, depending on whether the target is smaller or larger, it restricts the search to the left or right half. This halving of the search region drastically reduces the number of elements to be examined, improving efficiency to O(log n). However, its limitations include the requirement for sorted data, which may involve an O(n log n) sorting overhead if not already sorted, and its unsuitability for non-indexed structures like linked lists .

The Linear Search algorithm works by iterating over each element of an array sequentially to find a particular key. If the key is found, the index is returned; otherwise, the search concludes when the entire array is traversed without finding the key. The worst-case time complexity occurs when the key is not present, requiring a complete traversal of the array, resulting in O(n) complexity . The average-case complexity is also O(n), as it assumes a uniform distribution of key occurrences . The best case happens when the key is the first element, offering a time complexity of O(1).

As the input data size increases exponentially, the efficiency of the Linear Search algorithm significantly deteriorates. The time complexity of Linear Search is O(n), meaning each additional element proportionally increases the time required for a search operation. Exponential growth in data size leads to an exponential increase in time taken to search for elements, making it impractical for very large datasets . This linear relationship between time and data size stands in contrast to more efficient algorithms like Binary Search with logarithmic complexity, which handle large datasets more effectively .

Binary Search involves dividing a sorted array into halves to locate a target element efficiently. After determining the array's middle element, if it matches the search target, the search is complete. If the target is smaller, the search continues in the left half of the array; if larger, in the right half. This process is recursively or iteratively repeated until the target is found or the search range is exhausted . The key to Binary Search's efficiency is having a sorted array, as unsorted data invalidates the assumption of fixed positions for dividing .

Linear Search might be preferred when dealing with unsorted arrays, as it does not require pre-sorting like Binary Search does, making it more versatile for certain situations where sorting is computationally expensive or unnecessary . Additionally, for very small datasets, the simplicity and ease of implementation of Linear Search can outweigh its inefficiency, as the overhead of sorting required for Binary Search would not justify the time saved . Furthermore, Linear Search can be applied to data structures not readily sortable, such as linked lists .

Bubble Sort can be optimized by introducing a flag to check if any elements were swapped during a pass. If no swaps occur, the array is already sorted, and further passes can be stopped early, avoiding unnecessary iterations . This slightly reduces the number of comparisons in some best-case scenarios, where the array is already or nearly sorted. Additionally, the sorting algorithm can skip checks over the last elements of each pass, as each pass moves the next-largest element to its correct position .

The name 'Bubble Sort' derives from the way smaller or lighter elements in the dataset gradually 'bubble up' to the top of the list, akin to bubbles rising in water . Through successive passes and comparisons, elements that are lighter (in a metaphorical sense) move towards the beginning of the array, whereas heavier elements sink to the end. This iterative swapping of adjacent elements until no unsorted pairs remain justifies the 'bubbling' metaphor .

Bubble Sort operates by repeatedly swapping adjacent elements if they are in the wrong order, effectively 'bubbling' larger elements to the end. It continues this process until the entire array is sorted. The algorithm's time complexity is O(n^2) in the worst case due to the need to perform multiple passes over the array . Selection Sort, on the other hand, divides the array into a sorted and an unsorted region. It repeatedly selects the smallest (or largest) element from the unsorted region and moves it to the end of the sorted region. Like Bubble Sort, its worst-case time complexity is O(n^2), but it generally performs fewer swaps .

Bubble Sort uses nested loops where the outer loop represents each pass through the array, and the inner loop handles the comparison and potential swapping of adjacent elements. The outer loop runs from the first to the last index-1, representing the number of passes required to ensure the array is fully sorted . The inner loop iterates over the array for each pass (decreasing in each pass due to sorted elements 'bubbling' up), comparing adjacent elements and swapping them if they are in the wrong order, which is crucial for positioning the larger elements towards the end .

You might also like