ICOM 4015 Advanced Programming Lecture 4 Bsqueda y
ICOM 4015 Advanced Programming Lecture 4 Búsqueda y Ordenamiento II Sorting Algorithms Reading: LNN Chapters 9, 10 & 16 Prof. Bienvenido Vélez 9/17/2020 ICOM 4015 1
Busqueda y Ordenamiento II Outline • Searching Arrays – Sequential search – Binary search 9/17/2020 ICOM 4015 2
Searching Algorithms Main Function // search. cc // Implements sequential and binary search algorithms #include <iostream> // Forward declarations template <class TYPE> int sequential. Search(TYPE key, TYPE list[], int length); template<class TYPE> int binary. Search(TYPE key, TYPE list[], int length); template <class TYPE> Static internal. Binary. Search (TYPE key, TYPE list[], int length, int i, int j); int main() { int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; cout << "Sequential. Search Position of 9 is " << sequential. Search(9, a, 9) << endl; cout << "Binary. Search Position of 9 is " << binary. Search(9, a, 9) << endl; cout << "Sequential. Search Position of 10 is " << sequential. Search(10, a, 9) << endl; cout << "Binary. Search Position of 10 is " << binary. Search(10, a, 9) << endl; } 9/17/2020 ICOM 4015 3
Example 1 Output [bvelez@amadeus] ~/icom 4015/lec 12 >>search Sequential. Search Position of 9 is 8 Binary. Search Position of 9 is 8 Sequential. Search Position of 10 is -1 Binary. Search Position of 10 is -1 [bvelez@amadeus] ~/icom 4015/lec 12 >> 9/17/2020 ICOM 4015 4
Sequential Search Implementation const int NOT_FOUND = -1; template <class TYPE> int sequential. Search(TYPE key, TYPE list[], int length) { int pos = 0; while ((pos < length) && (list[pos] != key)) { pos++; } return ((pos < length) ? pos : NOT_FOUND); } 1 2 3 4 5 6 7 8 9 9/17/2020 Start searching for key = 8 comparisons = 8 ICOM 4015 5
Binary Search Example 1 2 3 4 5 6 7 8 9 Start (m = 4) m=6 m=7 searching for key = 8 comparisons = 3 9/17/2020 ICOM 4015 6
Binary Search Recursive Implementation template<class TYPE> static int binary. Search(TYPE key, TYPE list[], int length) { return internal. Binary. Search(key, list, length, 0, length-1); } template <class TYPE> internal. Binary. Search(TYPE key, TYPE list[], int length, int i, int j) { if (i > j) { return NOT_FOUND; } int m = (i + j) / 2; if (key == list[m]) { return m; } else if (key < list[m]) { return internal. Binary. Search(key, list, length, i, m-1); } else { return internal. Binary. Search(key, list, length, m+1, j); } } 9/17/2020 ICOM 4015 7
Searching Arrays Summary of Concepts • Sequential search – a linear algorithm • comparisons = O(N) • Binary search – A logarithmic algorithm • comparisons = O(log N) – But requires array to be pre-sorted – An example of a theoretically optimal algorithm! 9/17/2020 ICOM 4015 8
- Slides: 8