MSIS 655 Advanced Business Applications Programming Week 12
MSIS 655 Advanced Business Applications Programming Week 12 Searching and Sorting (Ch. 16) 10/2/2020 12. 1
Introduction Searching n Determining whether a search key is present in data Sorting n 10/2/2020 Places data in order based on one or more sort keys 2
Searching Algorithms Linear search n n Searches each element sequentially If search key is not present w Tests each element w When algorithm reaches end of array, informs user search key is not present n If search key is present w Test each element until it finds a match 10/2/2020 3
Linear. Array. java (Fig. 16. 2 p. 788) 10/2/2020 4
Efficiency of Linear Search Big O Notation n n 10/2/2020 Indicates the worst-case run time for an algorithm O(1): Constant O(n): Linear O(n 2): Quadratic 5
Binary Search n n n More efficient than linear search Requires elements to be sorted Tests the middle element in an array w If it is the search key, algorithm returns w Otherwise, if the search key is smaller, eliminates larger half of array w If the search key is larger, eliminates smaller half of array n 10/2/2020 Each iteration eliminates half of the remaining elements 6
Binary. Array. java (pp. 792 -793) 10/2/2020 7
Efficiency of Binary Search n n n 10/2/2020 Each comparison halves the size of the remaining array Results in O(log n) Called logarithmic run time 8
Sorting Algorithms Sorting data n Placing data into some particular order w A bank sorts checks by account number w Telephone companies sort accounts by name n n 10/2/2020 End result is always the same – a sorted array Choice of algorithm affects how you achieve the result and, most importantly, how fast you achieve the result 9
Selection Sort n n 10/2/2020 Simple, but inefficient sorting algorithm First iteration selects smallest element in array and swaps it with the first element Each iteration selects the smallest remaining unsorted element and swaps it with the next element at the front of the array After i iterations, the smallest i elements will be sorted in the first i elements of the array 10
Selection. Sort. java (pp. 798 -799) 10/2/2020 11
Efficiency of Selection Sort Selection sort n Outer for loop iterates over n – 1 elements Inner for loop iterates over remaining elements in the array Results in O(n 2) 10/2/2020 12 n n
Insertion Sort n n 10/2/2020 Another simple, but inefficient sorting algorithm First pass takes the second element and inserts it into the correct order with the first element Each iteration takes the next element in the array and inserts it into the sorted elements at the beginning of the array After i iterations, the first i elements of the array are in sorted order 13
10/2/2020 14
Merge Sort Combination of Sort algorithm and recursion To be continued… 10/2/2020 15
Lab activities (Week 12) Exercises (pp. 814 -815) 16. 5, 16. 6 Advanced: 16. 7 10/2/2020 16
- Slides: 16