CIS 1202 Chapter 8

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

The binary search algorithm does this

repeatedly divides the portion of an array being searched in half.

MAX_PRODNUM

A constant integer initialized with the highest product number.

MIN_PRODNUM

A constant integer initialized with the lowest product number.

NUM_PRODS

A constant integer initialized with the number of products the Demetris Leadership Center sells. This value will be used in the definition of the program's array.

Search Algorithm

A method of locating a specific item in a larger collection of data. This section discusses two algorithms for searching the contents of an array.

binarySearch

A standard binary search routine. Searches an array for a specified value. If the value is found, its subscript is returned. If the value is not found, -1 is returned.

prices

Array of doubles. Holds each product's price

prices

Array of doubles. Holds each product's price.

sales

Array of doubles. Holds the computed sales amounts (in dollars) of each product.

id

Array of integers. Holds each product's number

prodNum

Array of ints. Holds each product's number

units

Array of ints. Holds each product's number of units sold.

description

Array of strings, initialized with the descriptions of each product.

title

Array of strings, initialized with the titles of products

What is an important difference between vectors and arrays?

By default, vectors are passed by value, whereas arrays are only passed by reference. If you want to change a value in a vector argument, it must be passed into a reference parameter. Reference vector parameters are also used in the calcSales and dualSort functions. NOTE: each time a value is added to a vector, the push_back member function is called. This is because the [] operator cannot be used to store a new element in a vector. It can only be used to store a value in an existing element or read a value from an existing element

Function getProdNum pseudocode

Display a prompt to enter a product number. Read prodNum. While prodNum is invalid Display an error message. Read prodNum. End While. Return prodNum.

showOrder in pseudocode

Display heading. For index variable is set to each subscript of the arrays from 0 through the last subscript Display id[index]. Display sales[index]. End For.

calcSales

Calculates each product's sales.

showOrder

Displays a list of the product numbers and sales amounts from the sorted sales and prodNum arrays.

showTotals

Displays the total number of units sold and the total sales amount for the period.

bubble sort in pseudocode

Do Set swap flag to false. For count is set to each subscript in array from 0 through the next-to-last subscript If array[count] is greater than array[count + 1] Swap the contents of array[count] and array[count + 1]. Set swap flag to true. End If. End For. While any elements have been swapped.

Why is binary search so efficient?

Every time it makes a comparison and fails to find the desired item, it eliminates half of the remaining portion of the array that must be searched. For example, consider an array with 1,000 elements. If the binary search fails to find an item on the first attempt, the number of elements that remains to be searched is 500. If the item is not found on the second attempt, the number of elements that remains to be searched is 250

The selection sort scans the array, starting at element 0, and locates the element with the smallest value. The contents of this element are then swapped with the contents of element 0. In this example, the 1 stored in element 5 is swapped with the 5 stored in element 0. After the exchange, the array would appear as

Example: 7 0Element 2 1Element 3 2Element 8 3Element 9 4Element 1 5Element into 1 5Element ..... 7 0Element

The bubble sort starts by comparing the first two elements in the array. If element 0 is greater than element 1, they are exchanged

Example: 7 0Element 2 1Element 3 2Element 8 3Element 9 4Element 1 5Element into 2 0Element 7 1Element etc...

calcSales in pseudocode

For index is set to each subscript in the arrays from 0 through the last subscript. Set sales[index] to units[index] times prices[index]. End For.

selection sort algorithm in pseudocode

For startScan is set to each subscript in array from 0 through the next-to-last subscript Set index variable to startScan. Set minIndex variable to startScan. Set minValue variable to array[startScan]. For index is set to each subscript in array from (startScan + 1) through the last subscript If array[index] is less than minValue Set minValue to array[index]. Set minIndex to index. End If. End For. Set array[minIndex] to array[startScan]. Set array[startScan] to minValue. End For.

dualSort in pseudocode

For startScan variable is set to each subscript in array from 0 through the next-to-last subscript Set index variable to startScan. Set maxIndex variable to startScan. Set tempId variable to id[startScan]. Set maxValue variable to sales[startScan]. For index variable is set to each subscript in array from (startScan + 1) through the last subscript If sales[index] is greater than maxValue Set maxValue to sales[index]. Set tempId to tempId[index]. Set maxIndex to index. End If. End For. Set sales[maxIndex] to sales[startScan]. Set id[maxIndex] = id[startScan]. Set sales[startScan] to maxValue. Set id[startScan] = tempId. End For.

N/2

In an average case involving an array of N elements, how many times will a linear search function have to read the array to locate a specific value?

How does a binary search work?

Instead of testing the array's first element, this algorithm starts with the element in the middle. If that element happens to contain the desired value, then the search is over. Otherwise, the value in the middle element is either greater than or less than the value being searched for. If it is greater, then the desired value (if it is in the list) will be found somewhere in the first half of the array. If it is less, then the desired value (again, if it is in the list) will be found somewhere in the last half of the array. In either case, half of the array's elements have been eliminated from further searching.

Which of the following describes the way the bubble sort works?

It makes several passes through an array and causes the larger values to move gradually toward the end of the array with each pass.

How do you sort and search algorithms using STL vectors?

Once you have properly defined an STL vector and populated it with values, you may sort and search the vector with the algorithms presented in this chapter. Simply substitute the vector syntax for the array syntax when necessary.

getProdNum

Prompts the user to enter a product number. The function validates input and rejects any value outside the range of correct product numbers.

showTotals in pseudocode

Set totalUnits variable to 0. Set totalSales variable to 0.0. For index variable is set to each subscript in the arrays from 0 through the last subscript Add units[index] to totalUnits[index]. Add sales[index] to totalSales. End For. Display totalUnits with appropriate heading. Display totalSales with appropriate heading.

Linear Search Algorithm

Sometimes called a sequential search, it uses a loop to sequentially step through an array, starting with the first element. It compares each element with the value being searched for and stops when either the value is found or the end of the array is encountered. If the value being searched for is not in the array, the algorithm will unsuccessfully search to the end of the array.

dualSort

Sorts the sales array so the elements are ordered from highest to lowest. The prodNum array is ordered so the product numbers correspond with the correct sales figures in the sorted sales array.

int binarySearch(const int array[], int numElems, int value) { int first = 0, // First array element last = numElems − 1, // Last array element middle, // Midpoint of search position = −1; // Position of search value bool found = false; // Flag while (!found && first <= last) { middle = (first + last) / 2; // Calculate midpoint if (array[middle] == value) // If value is found at mid { found = true; position = middle; } else if (array[middle] > value) // If value is in lower half last = middle − 1; else first = middle + 1; // If value is in upper half } return position; }

The function binarySearch shown in the following example is used to perform a binary search on an integer array. The first parameter, array, which has a maximum of numElems elements, is searched for an occurrence of the number stored in value. If the number is found, its array subscript is returned. Otherwise, -1 is returned indicating the value did not appear in the array.

int searchList(const int list[], int numElems, int value) { int index = 0; // Used as a subscript to search array int position = −1; // To record position of search value bool found = false; // Flag to indicate if the value was found while (index < numElems && !found) { if (list[index] == value) // If the value is found { found = true; // Set the flag position = index; // Record the value's subscript } index++; // Go to the next element } return position; // Return the position, or −1 }

The function searchList shown below is an example of C++ code used to perform a linear search on an integer array. The array list, which has a maximum of numElems elements, is searched for an occurrence of the number stored in value. If the number is found, its array subscript is returned. Otherwise, −1 is returned indicating the value did not appear in the array

main

The program's main function. It calls the program's other functions

The Selection Sort

The smallest value in the array is located and moved to element 0. Then the next smallest value is located and moved to element 1. This process continues until all of the elements have been placed in their proper order

Which of the following describes the way the selection sort works?

The smallest value in the array is located and moved to element 0. Then the next smallest value is located and moved to element 1. This process continues until all of the elements have been placed in their proper order.

STL vectors

The sorting and searching algorithms you have studied in this chapter may be applied to _____ as well as arrays

Set first index to 0. Set last index to the last subscript in the array. Set found to false. Set position to −1. While found is not true and first is less than or equal to last Set middle to the subscript halfway between array[first] and array[last]. If array[middle] equals the desired value Set found to true. Set position to middle. Else If array[middle] is greater than the desired value Set last to middle − 1. Else Set first to middle + 1. End If. End While. Return position.

This algorithm of pseudocode uses three index variables: first, last, and middle. The first and last variables mark the boundaries of the portion of the array currently being searched. They are initialized with the subscripts of the array's first and last elements. The subscript of the element halfway between first and last is calculated and stored in the middle variable. If the element in the middle of the array does not contain the search value, the first or last variables are adjusted so that only the top or bottom half of the array is searched during the next iteration. This cuts the portion of the array being searched in half each time the loop fails to locate the search value.

The binary search algorithm will not work properly unless the values in the array are sorted.

True

displayProd

Uses a common subscript into the title, description, and prices arrays to display the title, description, and price of a product.

Bubble Sort

an easy way to arrange data in ascending or descending order. If an array is sorted in ascending order, it means the values in the array are stored from lowest to highest. If the values are sorted in descending order, they are stored from highest to lowest.

Powers of 2

are used to calculate the maximum number of comparisons the binary search will make on an array of any size. For example, a maximum of 16 comparisons will be made on an array of 50,000 elements (2^16 = 65,536), and a maximum of 20 comparisons will be made on an array of 1,000,000 elements (2^20 = 1,048,576).

Why is the bubble sort inefficient for large arrays?

because items only move by one element at a time.

Function main C++ code

do { // Get the desired product number. prodNum = getProdNum(); // Search for the product number. index = binarySearch(id, NUM_PRODS, prodNum); // Display the results of the search. if (index == −1) cout << "That product number was not found.\n"; else displayProd(title, description, prices, index); // Does the user want to do this again? cout << "Would you like to look up another product? (y/n) "; cin >> again; } while (again == 'y' || again == 'Y');

Function main pseudocode

do Call getProdNum. Call binarySearch. If binarySearch returned −1 Inform the user that the product number was not found. else Call displayProd. End If. Ask the user if the program should repeat. While the user wants to repeat the program.

Function getProdNum C++ code

int getProdNum() { int prodNum; cout << "Enter the item's product number: "; cin >> prodNum; // Validate input. while (prodNum &lt; MIN_PRODNUM || prodNum > MAX_PRODNUM) { cout << "Enter a number in the range of " << MIN_PRODNUM; cout <<" through " << MAX_PRODNUM << ".\n"; cin >> prodNum; } return prodNum; }

Binary Search

is a clever algorithm that is much more efficient than the linear search

sorting algorithm

is a technique for scanning through an array and rearranging its contents in some specific order.

Downside Of Linear Search

its inefficiency. If the array being searched contains 20,000 elements, the algorithm will have to look at all 20,000 elements in order to find a value stored in the last element (so the algorithm actually reads an element of the array 20,000 times).

calcSales in C++ code

void calcSales(const int units[], const double prices[], double sales[], int num) { for (int index = 0; index < num; index++) sales[index] = units[index] * prices[index]; }

displayProd Function C++ code

void displayProd(const string title[], const string desc[], const double price[], int index) { cout << "Title: " << title[index] << endl; cout << "Description: " << desc[index] << endl; cout << "Price: $" << price[index] << endl; }

dualSort in C++ code

void dualSort(int id[], double sales[], int size) { int startScan, maxIndex, tempId; double maxValue; for (startScan = 0; startScan < (size − 1); startScan++) { maxIndex = startScan; maxValue = sales[startScan]; tempId = id[startScan]; for(int index = startScan + 1; index < size; index++) { if (sales[index] > maxValue) { maxValue = sales[index]; tempId = id[index]; maxIndex = index; } } sales[maxIndex] = sales[startScan]; id[maxIndex] = id[startScan]; sales[startScan] = maxValue; id[startScan] = tempId; } }

selection sort algorithm in c++ code

void selectionSort(int array[], int size) { int startScan, minIndex, minValue; for (startScan = 0; startScan < (size − 1); startScan++) { minIndex = startScan; minValue = array[startScan]; for(int index = startScan + 1; index < size; index++) { if (array[index] < minValue) { minValue = array[index]; minIndex = index; } } array[minIndex] = array[startScan]; array[startScan] = minValue; } }

showOrder in C++ code

void showOrder(const double sales[], const int id[], int num) { cout << "Product Number\tSales\n"; cout << "----------------------------------\n"; for (int index = 0; index < num; index++) { cout <<; id[index] <<; "\t\t$"; cout << setw(8) << sales[index] << endl; } cout << endl; }

showTotals in in C++ code

void showTotals(const double sales[], const int units[], int num) { int totalUnits = 0; double totalSales = 0.0; for (int index = 0; index < num; index++) { totalUnits += units[index]; totalSales += sales[index]; } cout <<"Total Units Sold: " << totalUnits << endl; cout << "Total Sales: $" << totalSales << endl; }

Bubble Sort C++ Code. NOTE: Inside the function is a for loop nested inside a do-while loop. The for loop sequences through the entire array, comparing each element with its neighbor and swapping them if necessary. Anytime two elements are exchanged, the flag variable swap is set to true. The for loop must be executed repeatedly until it can sequence through the entire array without making any exchanges. This is why it is nested inside a do-while loop. The do-while loop sets swap to false, and then executes the for loop. If swap is set to true after the for loop has finished, the do-while loop repeats.

void sortArray(int array[], int size) { bool swap; int temp; do { swap = false; for (int count = 0; count &lt; (size − 1); count++) { if (array[count] &gt; array[count + 1]) { temp = array[count]; array[count] = array[count + 1]; array[count + 1] = temp; swap = true; } } } while (swap); }


संबंधित स्टडी सेट्स

Anatomy and Physiology- Chapter 1 Homework

View Set

RN professionalism and Leadership Assessment

View Set

Random Process-M1-Probability Theory and Random Processes

View Set

XCEL Chapter 11 - Laws and Rules

View Set