Searching and Sorting Algorithms Handout
Searching and Sorting Algorithms Handout
Binary search: Binary search, also known as half interval search, logarithmic
search, or binary chop, compares the target element from the middle of the element
of array; if it is not found then the half in which target cannot lie is eliminated and
the search continues in the remaining half until the desired target is found. If the
search ends with the remaining other half empty, it means the target element is not
in the array. Binary search more efficient then linear search because it searches the
element in minimum number of comparison.
Bubble Sort: The algorithm works by comparing each item in the list with the item
next to it, and swapping them if required. In other words, the largest element has
bubbled to the top of the array. The algorithm repeats this process until it makes a
pass all the way through the list without swapping any items.
7, 5, 2, 4, 3, 9
5, 7, 2, 4, 3, 9
5, 2, 7, 4, 3, 9
5, 2, 4, 7, 3, 9
5, 2, 4, 3, 7, 9
5, 2, 4, 3, 7, 9
Selection Sort : The algorithm works by selecting the smallest unsorted item and
then swapping it with the item in the next position to be filled.
The selection sort works as follows: you look through the entire array for the
smallest element, once you find it you swap it (the smallest element) with the first
element of the array. Then you look for the smallest element in the remaining array
(an array without the first element) and swap it with the second element. Then you
look for the smallest element in the remaining array (an array without first and
second elements) and swap it with the third element, and so on. Here is an
example,
Example.
Insertion Sort
To sort unordered list of elements, we remove its entries one at a time and then
insert each of them into a sorted part (initially empty):
void insertionSort(int ar[], int n)
{
int i,j,index;
for (i=1; i ‹ n; i++)
{
index = ar[i];
j = i;
while (j > 0 && ar[j-1] > index)
{
ar[j] = ar[j-1];
j--;
}
ar[j] = index;
}
}
Example. We color a sorted part in green, and an unsorted part in black. Here is an
insertion sort step by step. We take an element from unsorted part and compare it
with elements in sorted part, moving fr0m right to left.