Lect 4 Sorting and Searching Algorithm
Lect 4 Sorting and Searching Algorithm
Fitsum Admasu
Department of Computer Science
Addis Ababa University
1
Binary Search Sorting Algorithms
Example Implementation: • Sorting is one of the most important operations performed by
int Binary_Search(int list[],int k) { computers.
int left = 0; else • Sorting is a process of reordering a list of items in either
int right= n - 1; left = mid + 1; increasing or decreasing order.
int found = 0; }
• The following are simple sorting algorithms used to sort small-
do{ }
sized lists.
mid = (left + right) / 2; while(found = = 0&& left <= right);
– Insertion Sort
if(key == list[mid])
– Selection Sort
found=1; if(found == 0)
– Bubble Sort
else{ index = -1;
if(key < list[mid]) else
right = mid - 1; index = mid;
return index;
}
2
Selection Sort Selection Sort
Implementation:
• Basic Idea: void selection_sort(int list[])
– Loop through the array from i= 0 to n - 1. {
– Select the smallest element in the array from i to n int i, j, smallest;
– Swap this value with value at position i. for(i = 0; i < n; i++){
smallest = i;
for(j = i + 1; j < n; j++){
if(list[j] < list[smallest])
smallest = j;
}//end of inner loop
temp = list[smallest];
list[smallest] = list[i];
list[i] = temp;
} //end of outer loop
}//end of selection_sort
3
Basic characteristics of sorting algorithms: Basic characteristics of sorting algorithms: