Presentation is loading. Please wait.

Presentation is loading. Please wait.

ADT LIST So far we have seen the following operations on a “list”:

Similar presentations


Presentation on theme: "ADT LIST So far we have seen the following operations on a “list”:"— Presentation transcript:

1 ADT LIST So far we have seen the following operations on a “list”: Adding an element Deleting an element Sorting the list for display Computing statistics on a list of numeric values Last operation Finding an element in a list

2 Finding an element is important:
FOR DELETION: usually you must “find” the element before deleting it…. FOR INSERTION: must find the place to insert an element (if not in alphabetic order)…. TO PRINT: i.e., find students name & print grade

3 4.8 Searching Arrays: Linear Search and
Search array for a key value Linear search Key value is the value to be searched for. It is usually inputted by the user. Compare each element of array with key value Start at one end, go to other If the element is found, return the index number of the array. Remember --- we do not usually need to return the value, we know the value since it is what we were searching for. We need to know the POSITION of the value, i.e., its index.

4 Finding an element in an array
SEARCHING Finding an element in an array Example: Given an array which contains a list of integers, find the index of a particular integer. index of 24 is index of 100 is 6 index of 35 is NOT FOUND

5 Takes array, search key, and array size.
// Fig. 4.19: fig04_19.cpp // Linear search of an array. #include <iostream> 4 using std::cout; using std::cin; using std::endl; 8 int linearSearch( const int [], int, int ); // prototype 10 11 int main() 12 { const int arraySize = 100; // size of array a int a[ arraySize ]; // create array a int searchKey; // value to locate in a 16 for ( int i = 0; i < arraySize; i++ ) // create some data a[ i ] = 2 * i; 19 cout << "Enter integer search key: "; cin >> searchKey; 22 // attempt to locate searchKey in array a int element = linearSearch( a, searchKey, arraySize ); 25 fig04_19.cpp (1 of 2) Takes array, search key, and array size.

6 fig04_19.cpp (2 of 2) 26 // display results 27 if ( element != -1 )
cout << "Found value in element " << element << endl; else cout << "Value not found" << endl; 31 return 0; // indicates successful termination 33 34 } // end main 35 36 // compare key to every element of array until location is 37 // found or until end of array is reached; return subscript of 38 // element if key or -1 if key not found 39 int linearSearch( const int array[], int key, int sizeOfArray ) 40 { for ( int j = 0; j < sizeOfArray; j++ ) 42 if ( array[ j ] == key ) // if found, return j; // return location of key 45 return -1; // key not found 47 48 } // end function linearSearch fig04_19.cpp (2 of 2)

7 fig04_19.cpp output (1 of 1) Enter integer search key: 36
Found value in element 18 Enter integer search key: 37 Value not found fig04_19.cpp output (1 of 1)

8 Linear Search Analysis
In the worst case, how many elements have to be compared? int linearSearch( const int array[], int key, int sizeOfArray ) 40 { for ( int j = 0; j < sizeOfArray; j++ ) 42 if ( array[ j ] == key ) // if found, return j; // return location of key 45 return -1; // key not found 47 48 } // end function linearSearch

9 Analysis IF an element is not in the array, all of the elements in the array have to be checked to determine that a particular element is not there. FOR EXAMPLE: if there are 10 elements in the array, 10 comparisons have to be made in the worst case. Therefore, if there are n elements in the array... n comparisons have to be made in the worst case

10 What if the array were already sorted?
Search for an element in a sorted array. Do we have to check all of the elements if we know something about the order of the array? No -- we can search until we know the element cannot appear anymore, i.e. array[j] > target. However in the worst case the # of comparisons is still the number of elements in the array, I.e. we have to check all of the elements in the array

11 Better Linear Search for Sorted Array
“Early termination” --- int linearSearchSorted( const int array[], int key, int sizeOfArray ) 40 { int j = 0; while ( j < sizeOfArray-1 && key < array[j]) j++ ; 42 if ( array[ j ] == key ) // if found, return j; // return location of key 45 return -1; // key not found 47 48 } // end function linearSearch

12 How to use a telephone book

13 To find the name “Randy Jackson”
you would not start with Aardvark and continue until you hit the name...

14 start Input item; set lower index to zero set upper index to size-1 no While lower index < upper index Return -1 Calculate midpoint yes Item == midpoint? Return index no found/not found Loop until yes Set lower index to midpoint + 1 Item > midpoint Set upper index to midpoint-1 no

15 1 3 4 7 29 45 69 100 134 156 200 Example 1: Looking for the number 140
high low low Midpoint high Midpoint high low Midpoint low high How many comparisons? 3

16 1 3 4 7 29 45 69 100 134 156 200 Example 1: Looking for the number 7
low Midpoint high Midpoint high low Midpoint low high How many comparisons? 3

17 fig04_20.cpp (1 of 6) 1 // Fig. 4.20: fig04_20.cpp
// Binary search of an array. #include <iostream> 4 using std::cout; using std::cin; using std::endl; 8 #include <iomanip> 10 11 using std::setw; 12 13 // function prototypes 14 int binarySearch( const int [], int, int, int, int ); 15 void printHeader( int ); 16 void printRow( const int [], int, int, int, int ); 17 18 int main() 19 { const int arraySize = 15; // size of array a int a[ arraySize ]; // create array a int key; // value to locate in a 23 for ( int i = 0; i < arraySize; i++ ) // create some data a[ i ] = 2 * i; 26 fig04_20.cpp (1 of 6)

18 27 cout << "Enter a number between 0 and 28: ";
cin >> key; 29 printHeader( arraySize ); 31 // search for key in array a int result = binarySearch( a, key, 0, arraySize - 1, arraySize ); 35 // display results if ( result != -1 ) cout << '\n' << key << " found in array element " << result << endl; else cout << '\n' << key << " not found" << endl; 42 return 0; // indicates successful termination 44 45 } // end main 46 fig04_20.cpp (2 of 6)

19 Determine middle element
47 // function to perform binary search of an array 48 int binarySearch( const int b[], int searchKey, int low, int high, int size ) 50 { int middle; 52 // loop until low subscript is greater than high subscript while ( low <= high ) { 55 // determine middle element of subarray being searched middle = ( low + high ) / 2; 58 // display subarray used in this loop iteration printRow( b, low, middle, high, size ); 61 fig04_20.cpp (3 of 6) Determine middle element

20 Use the rule of binary search: If key equals middle, match
54 while ( low <= high ) { 55 // determine middle element of subarray being searched middle = ( low + high ) / 2; 58 // display subarray used in this loop iteration printRow( b, low, middle, high, size ); // if searchKey matches middle element, return middle if ( searchKey == b[ middle ] ) // match return middle; 65 else 67 // if searchKey less than middle element, // set new high element if ( searchKey < b[ middle ] ) high = middle - 1; // search low end of array 72 // if searchKey greater than middle element, // set new low element else low = middle + 1; // search high end of array } 78 return -1; // searchKey not found 80 81 } // end function binarySearch Use the rule of binary search: If key equals middle, match If less, search low end If greater, search high end Loop sets low, middle and high dynamically. If searching the high end, the new low is the element above the middle.

21 fig04_20.cpp (5 of 6) 82 83 // print header for output
84 void printHeader( int size ) 85 { cout << "\nSubscripts:\n"; 87 // output column heads for ( int j = 0; j < size; j++ ) cout << setw( 3 ) << j << ' '; 91 cout << '\n'; // start new line of output 93 // output line of - characters for ( int k = 1; k <= 4 * size; k++ ) cout << '-'; 97 cout << endl; // start new line of output 99 100 } // end function printHeader 101 fig04_20.cpp (5 of 6)

22 102 // print one row of output showing the current
103 // part of the array being processed 104 void printRow( const int b[], int low, int mid, int high, int size ) 106 { // loop through entire array for ( int m = 0; m < size; m++ ) 109 // display spaces if outside current subarray range if ( m < low || m > high ) cout << " "; 113 // display middle element marked with a * else 116 if ( m == mid ) // mark middle value cout << setw( 3 ) << b[ m ] << '*'; 119 // display other elements in subarray else cout << setw( 3 ) << b[ m ] << ' '; 123 cout << endl; // start new line of output 125 126 } // end function printRow fig04_20.cpp (6 of 6)

23 fig04_20.cpp output (1 of 2) Enter a number between 0 and 28: 6
Enter a number between 0 and 28: 6 Subscripts: * * 6 found in array element 3 Enter a number between 0 and 28: 25 * 24 26* 28 24* 25 not found fig04_20.cpp output (1 of 2)

24 fig04_20.cpp output (2 of 2) Enter a number between 0 and 28: 8
Subscripts: * * 8 10* 12 8* 8 found in array element 4 fig04_20.cpp output (2 of 2)

25 SEARCH ALGORITHM BEST CASE WORST CASE
Sorted array: SEARCH ALGORITHM BEST CASE WORST CASE Entire array Linear Search 1 1 Binary Search The number of times you can divide the array by 2 = log2(#elems_in_array) *******

26 What does log2 mean? Z Z 22 2x Z 23 Z elements
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x is the number of times I can keep splitting the list until there is only 1 element left xxxxxxxxxxxxxxxxxxxxxxxx Z/2 elements xxxxxxxxxxx Z Z 2x =1? Log2 z = x 22 Z/2/2 elements xxxxxx Z Z/2/2/2 elements 23

27 Powers of 2 Below are tables for the power 2x x 2x 1 2 3 4 5 6 7 8 9 10 11 12 13 16 32 64 128 256 512 1024 2048 4096 8192 14 15 16 17 18 19 20 21 22 16384 32768 65536 131072 262144 524288

28 SEARCH ALGORITHM BEST CASE WORST CASE
n Linear Search 1 1 Log2(n) Binary Search For an ORDERED array of n elements

29 SEARCH ALGORITHM BEST CASE WORST CASE
What about an unsorted array? SEARCH ALGORITHM BEST CASE WORST CASE 1 Linear Search n NOT APPLICABLE Binary Search

30 4.7 Case Study: Computing Mean, Median and Mode Using Arrays
Average (sum/number of elements) Median Number in middle of sorted list 1, 2, 3, 4, 5 (3 is median) If even number of elements, take average of middle two Mode Number that occurs most often 1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)

31 fig04_17.cpp (1 of 8) 1 // Fig. 4.17: fig04_17.cpp
// This program introduces the topic of survey data analysis. // It computes the mean, median, and mode of the data. #include <iostream> 5 using std::cout; using std::endl; using std::fixed; using std::showpoint; 10 11 #include <iomanip> 12 13 using std::setw; 14 using std::setprecision; 15 16 void mean( const int [], int ); 17 void median( int [], int ); 18 void mode( int [], int [], int ); 19 void bubbleSort( int[], int ); 20 void printArray( const int[], int ); 21 22 int main() 23 { const int responseSize = 99; // size of array responses 25 fig04_17.cpp (1 of 8)

32 26 int frequency[ 10 ] = { 0 }; // initialize array frequency
27 // initialize array responses int response[ responseSize ] = { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9, , 8, 9, 5, 9, 8, 7, 8, 7, 8, , 7, 8, 9, 3, 9, 8, 7, 8, 7, , 8, 9, 8, 9, 8, 9, 7, 8, 9, , 7, 8, 7, 8, 7, 9, 8, 9, 2, , 8, 9, 8, 9, 8, 9, 7, 5, 3, , 6, 7, 2, 5, 3, 9, 4, 6, 4, , 8, 9, 6, 8, 7, 8, 9, 7, 8, , 4, 4, 2, 5, 3, 8, 7, 5, 6, , 5, 6, 1, 6, 5, 7, 8, 7 }; 40 // process responses mean( response, responseSize ); median( response, responseSize ); mode( frequency, response, responseSize ); 45 return 0; // indicates successful termination 47 48 } // end main 49 fig04_17.cpp (2 of 8)

33 50 // calculate average of all response values
51 void mean( const int answer[], int arraySize ) 52 { int total = 0; 54 cout << "********\n Mean\n********\n"; 56 // total response values for ( int i = 0; i < arraySize; i++ ) total += answer[ i ]; 60 // format and output results cout << fixed << setprecision( 4 ); 63 cout << "The mean is the average value of the data\n" << "items. The mean is equal to the total of\n" << "all the data items divided by the number\n" << "of data items (" << arraySize << "). The mean value for\nthis run is: " << total << " / " << arraySize << " = " << static_cast< double >( total ) / arraySize << "\n\n"; 72 73 } // end function mean 74 fig04_17.cpp (3 of 8) We cast to a double to get decimal points for the average (instead of an integer).

34 75 // sort array and determine median element's value
76 void median( int answer[], int size ) 77 { cout << "\n********\n Median\n********\n" << "The unsorted array of responses is"; 80 printArray( answer, size ); // output unsorted array 82 bubbleSort( answer, size ); // sort array 84 cout << "\n\nThe sorted array is"; printArray( answer, size ); // output sorted array 87 // display median element cout << "\n\nThe median is element " << size / 2 << " of\nthe sorted " << size << " element array.\nFor this run the median is " << answer[ size / 2 ] << "\n\n"; 93 94 } // end function median 95 fig04_17.cpp (4 of 8) Sort array by passing it to a function. This keeps the program modular.

35 fig04_17.cpp (5 of 8) 96 // determine most frequent response
97 void mode( int freq[], int answer[], int size ) 98 { int largest = 0; // represents largest frequency int modeValue = 0; // represents most frequent response 101 cout << "\n********\n Mode\n********\n"; 103 // initialize frequencies to 0 for ( int i = 1; i <= 9; i++ ) freq[ i ] = 0; 107 // summarize frequencies for ( int j = 0; j < size; j++ ) freq[ answer[ j ] ]; 111 // output headers for result columns cout << "Response" << setw( 11 ) << "Frequency" << setw( 19 ) << "Histogram\n\n" << setw( 55 ) << " \n" << setw( 56 ) << " \n\n"; 117 fig04_17.cpp (5 of 8)

36 // output results for ( int rating = 1; rating <= 9; rating++ ) { cout << setw( 8 ) << rating << setw( 11 ) << freq[ rating ] << " "; 122 // keep track of mode value and largest fequency value if ( freq[ rating ] > largest ) { largest = freq[ rating ]; modeValue = rating; 127 } // end if 129 // output histogram bar representing frequency value for ( int k = 1; k <= freq[ rating ]; k++ ) cout << '*'; 133 cout << '\n'; // begin new line of output 135 } // end outer for 137 // display the mode value cout << "The mode is the most frequent value.\n" << "For this run the mode is " << modeValue << " which occurred " << largest << " times." << endl; 142 143 } // end function mode The mode is the value that occurs most often (has the highest value in freq). fig04_17.cpp (6 of 8)

37 144 145 // function that sorts an array with bubble sort algorithm 146 void bubbleSort( int a[], int size ) 147 { int hold; // temporary location used to swap elements 149 // loop to control number of passes for ( int pass = 1; pass < size; pass++ ) 152 // loop to control number of comparisons per pass for ( int j = 0; j < size - 1; j++ ) 155 // swap elements if out of order if ( a[ j ] > a[ j + 1 ] ) { hold = a[ j ]; a[ j ] = a[ j + 1 ]; a[ j + 1 ] = hold; 161 } // end if 163 164 } // end function bubbleSort 165 fig04_17.cpp (7 of 8)

38 fig04_17.cpp (8 of 8) 166 // output array contents (20 values per row)
167 void printArray( const int a[], int size ) 168 { for ( int i = 0; i < size; i++ ) { 170 if ( i % 20 == 0 ) // begin new line every 20 values cout << endl; 173 cout << setw( 2 ) << a[ i ]; 175 } // end for 177 178 } // end function printArray fig04_17.cpp (8 of 8)

39 fig04_17.cpp output (1 of 2) ******** Mean
The mean is the average value of the data items. The mean is equal to the total of all the data items divided by the number of data items (99). The mean value for this run is: 681 / 99 = Median The unsorted array of responses is The sorted array is The median is element 49 of the sorted 99 element array. For this run the median is 7 fig04_17.cpp output (1 of 2)

40 fig04_17.cpp output (2 of 2) ******** Mode
Response Frequency Histogram * *** **** ***** ******** ********* *********************** *************************** ******************* The mode is the most frequent value. For this run the mode is 8 which occurred 27 times. fig04_17.cpp output (2 of 2)


Download ppt "ADT LIST So far we have seen the following operations on a “list”:"

Similar presentations


Ads by Google