Chapter 2 - Elementary Searching and Sorting Algorithms
Chapter 2 - Elementary Searching and Sorting Algorithms
Hawasa University
Chapter Two
Elementary Searching and Sorting Algorithms
Implementation:
int i;
bool found =false;
for(i=0;i<n;i++;)
if (DataElement[i]==key)
{
found=true;
break;
}
return (found);
Example
List index 0 1 2 3 4 5 6 7
Data C A E F N Q R K
Key=Q after six comparison the algorithm returns found
Key=X after 8 comparison the algorithm returns found false
What is the Big O of sequential searching algorithm?
◦ For searching algorithm the dominant factor is
comparison of keys
◦ How many comparisons are made in sequential
searching?
◦ The maximum number of comparison is n, i.e. O (n).
Binary search
We change our low to mid + 1 and find the new mid value again.
low = mid + 1 mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our
target value 31.
…cont
Implementation:
for (int i = 0; i < n-1; i++)
for (int j = n-1; j > i; j--)
if (data[j] < data[j-1])
swap(data[j],data[j-1]);
Cont’d…
Bubble sort Algorithm:
Compare each element (except the last one) with its neighbor to the right.
If they are out of order, swap them. This puts the largest element at the
very end The last element is now in the correct and final place.
Compare each element (except the last two) with its neighbor to the
right.
If they are out of order, swap them. This puts the second largest element
before last. The last two elements are now in their correct and final
places.
Compare each element (except the last three) with its neighbor to the
right.
Continue as above until you have no unsorted elements on the left.
It is the oldest, simplest, and slowest sort in use. It works by comparing
each item in a list with an item next to it, and swap them if required. This
causes the larger values to “bubble” to the end of the list while smaller
Analysis
Passes number of comparison number of swaps
1 n-1 n-1
2 n-2 n-2
. . .
. . .
. . .
n-1 1 1
total n(n-1)/2 n(n-1)/2
=O(n2)
• When the last element is put into its proper position the
list is sorted and the algorithm is done.
Algorithm
Insertion sort algorithm somewhat resembles Selection
Sort and Bubble sort.
Array is imaginary divided into two parts - sorted one
and unsorted one.
At the beginning, sorted part contains first element of
the array and unsorted one contains the rest.
At every step, algorithm takes first element in the
unsorted part and inserts it to the right place of the
sorted one.
When unsorted part becomes empty, algorithm stops.
Example
implementation
for (int i = 1; i <= n-1; i++)
{
for(int j = i;j>=1; j--)
{
if(list[j-1] > list[j]) example
{
int temp = list[j]; 21, 6 ,15, 23, 9
list[j] = list[j-1];
list[j-1] = temp;
}
else break;
}
}
}
Analysis