0% found this document useful (0 votes)
17 views64 pages

DS Unit 5

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 views64 pages

DS Unit 5

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/ 64

UNIT-V

SEARCHING TECHNIQUES

• Searching is the process of finding some particular


element in the list.
• If the element is present in the list, then the process
is called successful, and the process returns the
location/index of that element;
• Otherwise, the search is called unsuccessful.
• Two popular search methods are
Linear Search and
Binary Search.
LINEAR SEARCH

• Linear search is also called as sequential search


algorithm.
• It is the simplest searching algorithm.
• It is mainly used to find the element from an unsorted
and sorted array.
• In Linear search, we simply traverse the list
completely and match each element of the list with
the item whose location is to be found.
• If the match is found, then the location of the item is
returned; otherwise, the algorithm returns NULL.
LINEAR SEARCH

Algorithm:
Linear Search (Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n, then jump to step 7
Step 3: if A[i] = x then jump to step 6
Step 4: Set i to i + 1
Step 5: Go to step 2
Step 6: Print element x found at index i and jump to step 8
Step 7: Print element not found
Step 8: Exit
WORKING ON LINEAR SEARCH

unsorted array:
Let the elements of array are -

Let the element to be searched is K = 41

The value of K, i.e., 41, is not matched with the first element of the array.
So, move to the next element. And follow the same process until the
respective element is found.
WORKING ON LINEAR SEARCH

Now, the element to be


searched is found. So
algorithm will return the
index of the element
matched. Index is 5
Application of Linear Search Algorithm
• The linear search is applicable on both single
and multi-dimensional arrays.
• Unsorted and sorted arrays can be used.
• It is less complex, effective, and easy to
implement when the array contains a few
elements.
BINARY SEARCH

• It is a searching algorithm that searches for an element's


position in a sorted array only.
• If the elements are not sorted already, we need to sort
them first to apply the binary search technique.
• Sorted here means that the elements will be in increasing
order.
• Binary search follows the divide and conquer approach in
which the list is divided into two halves, and the item is
compared with the middle element of the list.
• If the match is found then, the location of the middle
element is returned.
• Otherwise, we search into either of the halves depending
upon the result produced through the match.
BINARY SEARCH

Algorithm:
Step 1: set beg= lower_bound, end=upper_bound, pos=-1
Step 2: repeat steps 3 and 4 while beg <=end
Step 3: set mid = (beg + end)/2
Step 4: if a[mid] = val
set pos = mid
print pos
print "value is present in the array"
else if a[mid] > val
set end = mid - 1
else
set beg = mid + 1
[end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the array"
[end of if]
WORKING OF BINARY SEARCH

Sorted array:

Let the element to search is, K = 60


Now, we need to find out mid of the array with the
formula:
(Start+finish)/2
So, in the given array –
start = 0
finish= 8
mid = (0 + 8)/2 = 4. Thus, 4 is in the middle of the array.
WORKING OF BINARY SEARCH
WORKING OF BINARY SEARCH

As we have found here the searched element, the index


of the matched element will return. INDEX IS 7
WORKING OF BINARY SEARCH

Advantages of Binary Search Algorithm


1.When it comes to compare large data, it is quite
efficient as it works on the technique to eliminate half
of the array element.
2.It has less compilation time and thus better time
complexity.
3.As it breaks the array in half, it is considered an
improvement over linear search.
Disadvantages of Binary Search Algorithm
4.It can only be implemented over a sorted array.
5.The process of sorting and searching in an unsorted
array will take time.
SORTING TECHNIQUES
SELECTION SORT

• Selection sort is a simple sorting algorithm.


• Selection sort is a comparison-based sorting
algorithm that divides the input list into a sorted part
at the beginning and an unsorted part at the end.
• This type of sorting is called Selection Sort as it
works by repeatedly sorting elements.
• That is: we first find the smallest value in the array
and exchange it with the element in the first position,
then find the second smallest element and
exchange it with the element in the second position,
and we continue the process in this way until the
entire array is sorted.
SELECTION SORT ALGORITHM

1. Set MIN to location 0.


2. Search the minimum element in the list.
3. Swap with value at location MIN.
4. Increment MIN to point to next element.
5. Repeat until the list is sorted.
WORKING OF SELECTION SORT ALGORITHM

• Let the elements of array are -

Now, for the first position in the sorted array, the


entire array is to be scanned sequentially
At present, 12 is stored at the first position, after
searching the entire array, it is found that 8 is the
smallest value.

So, swap 12 with 8. After the first iteration, 8 will appear at the first
position in the sorted array.
WORKING OF SELECTION SORT ALGORITHM

For the second position, where 29 is stored presently, we again sequentially scan the rest
of the items of unsorted array. After scanning, we find that 12 is the second lowest
element in the array that should be appeared at second position

Now, swap 29 with 12. After the second iteration, 12 will appear at the second
position in the sorted array. So, after two iterations, the two smallest values are
placed at the beginning in a sorted way.
WORKING OF SELECTION SORT ALGORITHM

The same process is applied to the rest of the array elements. Now, we
are showing a pictorial representation of the entire sorting process.

Now, the array is completely sorted.


PSEUDOCODE OF SELECTION SORT
ALGORITHM

void selectionSort(int arr[], int n) {


int i, j, minIndex, temp;
for (i = 0; i < n-1; i++) {
// Assume the first element is the minimum
minIndex = i;
// Find the minimum element in the unsorted portion of the array
for (j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element of the unsorted portion
temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
MERGE SORT

• Merge sort is a sorting technique technique based


on divide and conquer conquer technique
• Divide: Divide the list or array recursively into two
halves until it can no more be divided.
• Conquer: Each subarray is sorted individually using
the merge sort algorithm.
• Merge: The sorted subarrays are merged back
together in sorted order. The process continues until
all elements from both subarrays have been
merged.
MERGE SORT
WORKING OF MERGE SORT ALGORITHM

How it works:
• Divide the unsorted array into two sub-arrays, half
the size of the original.
• Continue to divide the sub-arrays as long as the
current piece of the array has more than one
element.
• Merge two sub-arrays together by always putting the
lowest value first.
• Keep merging until there are no sub-arrays left.
WORKING OF MERGE SORT ALGORITHM
WORKING OF MERGE SORT ALGORITHM
WORKING OF MERGE SORT ALGORITHM
WORKING OF MERGE SORT ALGORITHM

Therefore, the sorted list is [10, 27, 38, 43] .


WORKING OF MERGE SORT ALGORITHM
Quick Sort

• Quicksort is a sorting algorithm based on the divide and conquer approach where an

array is divided into subarrays by selecting a pivot element (element selected from

the array).
• While dividing the array, the pivot element should be positioned in such a way that

elements less than pivot are kept on the left side and elements greater than pivot are

on the right side of the pivot.


• The left and right subarrays are also divided using the same approach. This process

continues until each subarray contains a single element.


• At this point, elements are already sorted. Finally, elements are combined to form a

sorted array.
Working of Quick Sort Algorithm

First Element as Pivot


Working of Quicksort Algorithm
Working of Quicksort Algorithm
Quicksort Complexity

Time Complexity
Best O(n*log n)
Worst O(n2)
Average O(n*log n)
• Space Complexity O(log n)
Quick Sort Algorithm
quickSort(array, leftmostIndex, rightmostIndex)
if (leftmostIndex < rightmostIndex)
pivotIndex <- partition(array,leftmostIndex, rightmostIndex)
quickSort(array, leftmostIndex, pivotIndex - 1)
quickSort(array, pivotIndex, rightmostIndex)
partition(array, leftmostIndex, rightmostIndex)
set rightmostIndex as pivotIndex
storeIndex <- leftmostIndex - 1
for i <- leftmostIndex + 1 to rightmostIndex
if element[i] < pivotElement
swap element[i] and element[storeIndex]
storeIndex++
swap pivotElement and element[storeIndex+1]
return storeIndex + 1
Insertion Sort

• Insertion sort is a simple sorting algorithm that iteratively constructs a sorted section

of an array one element at a time. It is an in-place comparison-based method.


• The array is divided into two halves by the method: sorted and unsorted. The first

element of the array is first considered the sorted component, whereas the remaining

items are originally considered the unsorted component.


• The algorithm subsequently compares each unsorted element to the elements in the

sorted segment, beginning at the end, and adjusts the bigger elements one position to

the right until the unsorted element is found in the correct location.
• After determining the proper location, the unsorted element is placed into the sorted

component at that location.


Insertion Sort

Algorithm
The simple steps of achieving the insertion sort are listed
as follows -
Step 1 - If the element is the first element, assume that it
is already sorted. Return 1.
Step2 - Pick the next element, and store it separately in
a key.
Step3 - Now, compare the key with all elements in the
sorted array.
Step 4 - If the element in the sorted array is smaller than
the current element, then move to the next element. Else,
shift greater elements in the array towards the right.
Pseudocode for Insertion Sort

for i from 1 to n-1


key = arr[i]
j=i-1
while j >= 0 and arr[j] > key
arr[j+1] = arr[j]
j=j-1
arr[j+1] = key
SHELL SORT

• It is a sorting algorithm that is an extended version of


insertion sort.
• As similar to insertion sort, it is a comparison-based
and in-place sorting algorithm.
• This algorithm first sorts the elements that are far
away from each other, then it subsequently reduces
the gap between them. This gap is called
as interval.
WORKING OF SHELL SORT

Start with a Big Gap: Instead of comparing numbers next to each


other, Shell sort starts by comparing numbers that are several
positions apart. This gap can be half the size of the list, or some other
value.
Compare and Swap: For each pair of numbers that are far apart,
compare them. If they are in the wrong order, swap them. This step
helps move larger numbers toward the end of the list and smaller
numbers toward the beginning, even if they are far apart.
Reduce the Gap: After going through the list with the big gap, reduce
the gap and repeat the process. This time, the numbers being
compared are closer together.
Repeat Until Gap is 1: Keep reducing the gap until it’s just 1, which
means you’re doing a final pass like a regular insertion sort. By this
point, the list is mostly sorted, so this last step is quick.
SHELL SORT ALGORITHM

Step 1 − Start
Step 2 − Initialize the value of gap size, say h.
Step 3 − Divide the list into smaller sub-part. Each must have equal
intervals to h.
Step 4 − Sort these sub-lists using insertion sort.
Step 5 – Repeat this step 2 until the list is sorted.
Step 6 – Print a sorted list.
Step 7 – Stop.
SHELL SORT EXAMPLE

Let the elements of array


are -
In the first loop, n is equal to 8 (size of the array), so the elements are
lying at the interval of 4 (n/2 = 4). Elements will be compared and
swapped if they are not in order.
SHELL SORT EXAMPLE

In the second loop, elements are lying at the interval of 2 (n/4 = 2),
where n = 8.
Now, we are taking the interval of 2 to sort the rest of the array. With an
interval of 2, two sublists will be generated - {12, 25, 33, 40}, and {17,
8, 31, 42}.
SHELL SORT EXAMPLE

In the third loop, elements are lying at the interval of 1 (n/8 = 1), where n =
8. At last, we use the interval of value 1 to sort the rest of the array
elements. In this step, shell sort uses insertion sort to sort the array
elements.

Now, the array


is sorted in
ascending
order.
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
elements are swapped if they are not in order.
• This algorithm is not suitable for large data sets
BUBBLE SORT ALGORITHM

Step 1 − Check if the first element in the input array is


greater than the next element in the array.
Step 2 − If it is greater, swap the two elements; otherwise
move the pointer forward in the array.
Step 3 − Repeat Step 2 until we reach the end of the array.
Step 4 − Check if the elements are sorted; if not, repeat the
same process (Step 1 to Step 3) from the last element of the
array to the first.
Step 5 − The final output achieved is the sorted array.
BUBBLE SORT EXAMPLE
BUCKET SORT

• Bucket sort is a sorting algorithm that separate the


elements into multiple groups said to be buckets.
• Elements in bucket sort are first uniformly divided into
groups called buckets, and then they are sorted by any
other sorting algorithm.
• After that, elements are gathered in a sorted manner.
BUCKET SORT

The basic procedure of performing the bucket sort is given as


follows -
First, partition the range into a fixed number of buckets.
Then, toss every element into its appropriate bucket.
After that, sort each bucket individually by applying a sorting
algorithm.
And at last, concatenate all the sorted buckets.
BUCKET SORT
BUCKET SORT
COUNTING SORT

• Counting sort is an external sorting algorithm that assumes all


the input values are integers that lie between the range 0 and k.
• Then mathematical computations on these input values to
place them at the correct position in the output array.
• This algorithm makes use of a counter to count the frequency
of occurrence of the numbers and arrange them accordingly.
• Suppose, if a number ‘m’ occurs 5 times in the input sequence,
the counter value of the number will become 5 and it is
repeated 5 times in the output array.
COUNTING SORT
COUNTING SORT
COUNTING SORT
RADIX SORT

• Radix sort is the linear sorting algorithm that is used for integers.
• In Radix sort, there is digit by digit sorting is performed that is started from
the least significant digit to the most significant digit.
• The key idea behind Radix Sort is to exploit the concept of place value. It
assumes that sorting numbers digit by digit will eventually result in a fully
sorted list.
• The process of radix sort works similar to the sorting of students names,
according to the alphabetical order.
• In this case, there are 26 radix formed due to the 26 alphabets in English. In
the first pass, the names of students are grouped according to the ascending
order of the first letter of their names.
• After that, in the second pass, their names are grouped according to the
ascending order of the second letter of their name. And the process
continues until we find the sorted list.
RADIX SORT ALGORITHM

Algorithm
1.Find the Maximum Element: Determine the number with the
maximum digits to define the number of passes required.
2. Sort by Each Digit:
Start from the least significant digit (LSD) to the most
significant digit (MSD).
Use a stable sorting algorithm like Counting Sort at each digit
level.
3.Update and Repeat: Reorder the list based on each subsequent
digit until all digits are processed.
RADIX SORT

Working of Radix sort Algorithm


To perform radix sort on the array [170, 45, 75, 90, 802, 24, 2, 66], we follow
these steps:

Step 1: Find the largest element in the array, which is 802. It has
three digits, so we will iterate three times, once for each significant
place.

Step 2: Sort the elements based on the unit place digits (X=0). We
use a stable sorting technique, such as counting sort, to sort the
digits at each significant place.
RADIX SORT

Working of Radix sort Algorithm


RADIX SORT

Working of Radix sort Algorithm


RADIX SORT

Working of Radix sort Algorithm


RADIX SORT

Working of Radix sort Algorithm

You might also like