Unit III
Unit III
•Binary Search to find the element “J” in a given sorted list from
A-X
Three useful variations on the sequential search
algorithm are:
1) Sentinel search
2) Probability search
3) Ordered list search
• Sentinel Linear Search as the name suggests is a type of
Linear Search where the number of comparisons are reduced as
compared to a traditional linear search.
• So, the index to be checked will never be out of bounds of the array.
The number of comparisons in the worst case here will be (N + 2).
int last = array[N-1];
array[N-1] = item; // Here item is the search
element.
int i = 0;
while(array[i]!=item) if( (i < N-1) || (item == array[N-1]) )
{ {
i++; cout << " Item Found @ "<<i;
} }
array[N-1] = last; else
{
cout << " Item Not Found";
}
Here we see that the while loop makes only one comparison in each
iteration and it is sure that it will terminate since the last element of
the list is the search element itself. So in the worst case ( if the search
element does not exists in the list ) then there will be at most N+2
comparisons ( N comparisons in the while loop and 2 comparisons in
the if condition). Which is better than ( 2N+1 ) comparisons as found
in Simple Linear Search.
Take note that both the algorithms have time complexity of O(n).
Fibonacci Search is a comparison-based technique that uses
Fibonacci numbers to search an element in a sorted array.
When the user makes a request for specific records it will find
that index group first where that specific record is recorded.
Characteristics of Indexed Sequential Search:
3. The index is searched 1st then the array and guides the
search in the array.
Sorting is the process ordering a list of element in either
ascending or descending order.
1. Internal Sorting
2. External Sorting
Any sort algorithm that uses main memory exclusively during
the sorting is called as internal sort algorithm.
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Quick Sort
5. Shell Sort
6. Heap Sort
7. Radix Sort
8. Bucket Sort
Any sort algorithm that uses external memory, such as tape or
disk , during the sorting is called as external sort algorithm.
Example :
Sort efficiency is a measure of the relative efficiency of a sort
First Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not
know if it is completed. The algorithm needs one whole pass
without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
def bubbleSort(arr):
n = len(arr)
The above function always runs O(n^2) time even if the array is
sorted. It can be optimized by stopping the algorithm if inner
loop didn’t cause any swap.
for j in range(0, n-i-1):