Download presentation
Presentation is loading. Please wait.
Published byBryan Holland Modified over 9 years ago
1
Lecture 22: Arrays (cont)
2
2 Lecture Contents: t Searching in array: –linear search –binary search t Multidimensional arrays t Demo programs t Exercises
3
3 The problem Searching in array: to determine and return the location of a particular value (target) Classification of searching algorithms: t Linear search t Binary search t Search based on hash functions
4
4 43 Linear Search t The idea of a linear search is to walk through the entire array until a target value is located t If the target is not located, specific type of indicator needs to be returned
5
5 Linear search algorithm Problem: to search a target in array Given:1. array (populated collection of data items) 2. target Output:index of array element that matches the target OR -1 if there is no match
6
6 Linear search algorithm 1. Assume the target has not been found. 2. Start with the initial array element. 3.Repeat while the target is not found and there are more array elements { 4. If the current element matches the target 5. Set a flag to indicate the target was found Else 6. Advance to the next array element } // end of repeat 7. If the target was found 8. Return the target index as a search result Else 9. Return –1 as a search result.
7
7 Linear search implemented iteratively // Iterative Linear Search int LinSearchIterative(int target, int table[], int size) { int k = 0; while ( k < size ) { if (target == table[k]) return k; k++; } return -1; }
8
8 Linear search implemented iteratively How to call the function? int LinSearchIterative(int target, int table[], int size); void main() { int tar; int m[] = { 10, 15, 8, 30, 50, 40 }; int res; tar = 20; // test other value as well res = LinSearchIterative(tar, m, 6); if (res== -1) cout << “Target not found”; else cout << “Target found at position “ << res; }
9
9 Linear search implemented recursively – 1 st version // Recursive linear search int LinSearchRecursive(int target,int table[],int low,int high) { if (high < low) return -1; if (target == table[high]) return high; return LinSearchRecursive(target, table, low, high-1); }
10
10 Linear search implemented recursively – 2 nd version // Recursive linear search int LinSearchRecursive(int target, int table[], int low, int high) { if (high < low) return -1; if (target == table[low]) return low; return LinSearchRecursive(target, table, low+1, high); }
11
11 Linear search implemented recursively How to call the function?
12
12 Linear search - Time performance Array size of n Min nmr of iterations, target found in one step – 1 Max nmr of iterations, target not found- n Average nmr of iterations - (1+n) / 2
13
13 43 Binary Search t The idea of a binary search is not to walk through the entire array until a target value is located t If the target is not located, specific type of indicator needs to be returned
14
14 Binary search algorithm Problem: to search a target in array Given:1. sorted array (collection of data items) 2. target Output:index of array element that matches the target OR -1 if there is no match
15
15 Binary search algorithm 1. Assume the array is sorted and the target has not been found 2. Let low be the subscript of the initial array element. 3. Let high be the subscript of the last array element. 4. Repeat as long as high > low (low<=high) and the target has not been found { 5. Let mid be the subscript of the element halfway btw low and high 6. If the element at mid is the target 7. Return mid (the target index) as a search result Else 8. If the element at mid is > the target 9. Let high be mid–1 Else 10. Let low be mid+1 } // end of repeat 11. return –1
16
16 Binary search implemented iteratively // Iterative Binary search int BinSearchIterative(int target, int table[], int size) { int low, high, mid; low = 0; high = size - 1; while ( low <= high ) { mid = (low + high) / 2; if (target == table[mid]) return mid; if (target < table[mid]) high = mid - 1; if (target > table[mid]) low = mid + 1; } return -1; }
17
17 Binary search implemented iteratively How to call the function?
18
18 Binary search implemented recursively // Recursive Binary search int BinSearchRecursive(int target, int table[], int low, int high) { if (low > high) return -1; int mid; mid = (low + high) / 2; if (target == table[mid]) return mid; if (target < table[mid]) // low half of the table { // high = mid -1; return BinSearchRecursive(target, table, low, mid -1); } if (target > table[mid]) // high half of the table { // low = mid+1; return BinSearchRecursive(target, table, mid +1, high); }
19
19 Binary search implemented recursively How to call the function?
20
20 Binary search - Time performance Array size of n After 1 iteration – array size of n/2 = n / 2^1 After 2 iterations – array size of n / 4 = n / 2^2 … After x iterations – array size of 1 = n / 2^x n = 2 ^ xx = ln n
21
21 More on arrays Extract from Friedman/Koffman, chapter 9
22
Data Structures Arrays and Structs Chapter 9
23
23 37 9.5 Searching and Sorting Arrays t Look at 2 common array problems –Searching –Sorting t How do we go about finding the smallest number in an array? –Assume 1st is smallest and save its position –Look for one smaller –If you locate one smaller save its position
24
24 38 ArrayOperations.cpp // File: arrayOperations.cpp // Finds the subscript of the smallest value in a // subarray. // Returns the subscript of the smallest value // in the subarray consisting of elements // x[startindex] through x[endindex] // Returns -1 if the subarray bounds are invalid. // Pre: The subarray is defined and 0 <= // startIndex <= endIndex. // Post: x[minIndex] is the smallest value in // the array.
25
25 39 ArrayOperations.cpp int findIndexOfMin(const float x[], int startIndex, int endIndex) { // Local data... int minIndex; int i; // Validate subarray bounds if ((startIndex endIndex)) { cerr << "Error in subarray bounds" << endl;return -1; }
26
26 40 ArrayOperations.cpp // Assume the first element of subarray is // smallest and check the rest. // minIndex will contain subscript of smallest // examined so far. minIndex = startIndex; for (i = startIndex + 1; i <= endIndex; i++) if (x[i] < x[minIndex]) minIndex = i; // All elements are examined and minIndex is // the index of the smallest element. return minIndex; } // end findIndexOfMin
27
27 43 Linear Search t The idea of a linear search is to walk through the entire array until a target value is located t If the target is not located some type of indicator needs to be returned
28
28 44 ArrayOperations.cpp // Searches an integer array for a given element(target) // Array elements ranging from 0 to size - 1 are // searched for an element equal to target. // Pre: The target and array are defined. // Post: Returns the subscript of target if // found; otherwise, returns -1. int linSearch (const int items[], int target, int size) { for (int next = 0; next < size; next++) if (items[next] == target)return next; // All elements were tested without success. return -1; } // end linSearch
29
29 46 Sorting in Ascending Order Selection Sort t Idea of the selection sort is to locate the smallest value in the array t Then switch positions of this value and that in position [0] t We then increment the index and look again for the next smallest value and swap t Continue until sorted
30
30 47 ArrayOperations.cpp // Sorts an array (ascending order) using // selection sort algorithm // Uses exchange and findIndexOfMin // Sorts the data in array items (items[0] // through items[n-1]). // Pre: items is defined and n <= declared size // of actual argument array. // Post: The values in items[0] through items // [n-1] are in increasing order.
31
31 48 ArrayOperations.cpp void selSort(int items[], int n) { // Local data... int minSub; for (int i = 0; i < n-1; i++) { // Find index of smallest element in // unsorted section of items. minSub = findIndexOfMin(items, i, n-1); // Exchange items at position minSub and i exchange(items[minSub], items[i]); }
32
32 50 9.7 Analyzing Algorithms Big-O Notation t How to compare efficiency of various algorithms t A mathematical measuring stick to do quantitative analysis on algorithms t Typically sorting and searching t Based on looping constructs and placed into categories based on their efficiency t Big-O means “Order of Magnitude” t Most algorithms have Big-O published
33
33 51 Analyzing Algorithms Big-O Notation t Run time efficiency is in direct proportion to the number of elementary machine operations –Compares –Exchanges
34
34 52 Analyzing Algorithms Big-O Notation t Two independent loops –Sum of the loops is efficiency –n/2 + n^2 is Big-O(n^2) Example: for (k=1; k<=n/2; ++k)for (j=1; j<=n*n; ++j){ …}
35
35 53 Analyzing Algorithms Big-O Notation t Two nested loops –Product of the loops is efficiency –n/2 * n^2 = n^3/2 is Big-O(n^3) Example: for (k=1; k<=n/2; ++k) { for (j=1; j<=n*n; ++j) { }
36
36 Exercise 22.1-22.4 Build programs to illustrate: Linear search iteratively Linear search recursively Binary search iteratively Binary search recursively
37
37 Before lecture end Lecture: Arrays (cont) More to read: Friedman/Koffman, Chapter 09
38
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Data Structures: Arrays and Structs Problem Solving, Abstraction, and Design using C++ 5e by Frank L. Friedman and Elliot B. Koffman
39
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 39 9.5 Searching and Sorting Arrays Two common array processing problems –Searching –Sorting E.g. –look for a particular score, highest score, etc. –rearrange an array of scores in increasing order
40
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 40 Finding the Smallest Value 1. Assume the first element is smallest so far and save its subscript 2. For each array element after the first one 2.1 If the current element < the smallest so far 2.1.1 Save the subscript of current element
41
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 41 Listing 9.8 Function findIndexOfMin
42
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 42 Listing 9.8 Function findIndexOfMin (continued)
43
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 43 Array Search - Interface Input arguments –int items[ ]// array to search –int size// number of items in array –int target// item to find Output arguments –none Returns –if found, subscript of first location in array –if not found, -1
44
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 44 Array Search - Algorithm 1. For each array element 1.1 If the current element contains the target 1.2 Return the subscript of the current element 2. Return -1.
45
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 45 Listing 9.9 The function linSearch
46
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 46 Sorting an Array in Ascending Order Many programs execute more efficiently if data is in order before processing starts Possible to order in either ascending or descending arrangement Selection sort just one of many ways to do this –reuses previous components of search and swap operations
47
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 47 Selection Sort Input arguments float items[ ]// array to sort int n// number of items to sort Output arguments int items [ ]// original array sorted Local variables int i// subscript of first element int minSub// subscript of smallest item
48
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 48 Selection Sort - Algorithm 1. Starting with the first item in the array (subscript 0) and ending with the next-to-last-item: 1.1 Set i equal to the subscript of the first item in the subarray to be processed in the next steps 1.2 Find the subscript (minSub) of the smallest item in the subarray with subscripts ranging from i through n-1 1.3 Exchange the smallest item found in step 1.2 with item i
49
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 49 Listing 9.10 Function selSort
50
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 50 9.6 Analyzing Algorithms: Big-O Notation Need to estimate efficiency of algorithms in order to compare Approximate the effect on an algorithm of a change in the number of items, n, that the algorithm processes Look at how an algorithm’s execution time increases with n (i.e. its growth rate). –Expressed in terms of largest contributing factor of polynomial describing processing time
51
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 51 Table 9.4 Table values of n and n 2
52
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 52 Analysis of a Search Algorithm Search an array of n elements using linear search method Target can be anywhere in the array For random data, it’s equally likely target is at end of array as at beginning On average, must search n/2 array elements Linear search is O(n) process
53
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 53 Analysis of Sort Algorithm Focus on the number of array element comparisons and exchanges required For selection sort, requires n-1 comparisons for 1st pass, n-2 for 2nd, etc. Total number of comparisons is 1 + 2 + 3 +... + (n-2) + (n-1) which is n (n-1) = n 2 /2 - n/2 2 or O(n 2 )
54
54 Thank You For Your Attention
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.