The Ohio State University

Slides:



Advertisements
Similar presentations
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Advertisements

Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
C++ for Engineers and Scientists Third Edition
CSE202: Lecture 18The Ohio State University1 C++ Vector Class.
Chapter 8 Arrays and Strings
CSE202: Lecture 14The Ohio State University1 Arrays.
CSE202: Lecture 16The Ohio State University1 Two Dimensional Arrays.
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
Chapter 8 Arrays and Strings
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
CSE1222: Lecture 3The Ohio State University1. Assignment Operations  The C++ assignment operator is: =  Examples: x = 3 * 5; y = x – 7; y = y + 4; Do.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CHAPTER 6 ARRAYS IN C++ 2 nd Semester King Saud University College of Applied studies and Community Service CSC 1101 By: Fatimah Alakeel Edited.
COMPUTER PROGRAMMING. Array C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An.
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
Sahar Mosleh California State University San MarcosPage 1 One Dimensional Arrays: Structured data types.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Computer Skills2 / Scientific Colleges 1 Arrays Topics to cover: Arrays Data Types One-dimensional Arrays Two-dimensional Arrays.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Searching Arrays Linear search Binary search small arrays
The Ohio State University
The Ohio State University
Introduction to Computer Programming
Repetitive Structures
REPETITION CONTROL STRUCTURE
Chapter 6 Arrays in C++ 2nd Semester King Saud University
EGR 2261 Unit 9 One-dimensional Arrays
Computer Programming BCT 1113
Bill Tucker Austin Community College COSC 1315
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Programming fundamentals 2 Chapter 1:Array
Introduction to C++ October 2, 2017.
Object-Oriented Programming Using C++
C++ Arrays.
One-Dimensional Array Introduction Lesson xx
7 Arrays.
Compound Assignment Operators in C++
CNG 140 C Programming (Lecture set 8)
Data type List Definition:
Review for Final Exam.
CISC181 Introduction to Computer Science Dr
Lecture 12 Oct 16, 02.
Variables T.Najah Al_Subaie Kingdom of Saudi Arabia
Arrays Topics to cover: Arrays Data Types One-dimensional Arrays
If Statements.
Review for Final Exam.
7 Arrays.
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
CS 101 First Exam Review.
Programming Fundamental
ADT LIST So far we have seen the following operations on a “list”:
Presentation transcript:

The Ohio State University Arrays CSE1222: Lecture 13 The Ohio State University

The Ohio State University Programming Problem Write a program to: Read in a list of integers; Print the list in reverse order. CSE1222: Lecture 13 The Ohio State University

The Ohio State University Arrays (1) So far the variables we have made store one value at a time. If you need to store and use 50 integers, then 50 int variables must be declared. These variables are called atomic or scalar, which means they cannot be further divided into smaller pieces. CSE1222: Lecture 13 The Ohio State University

One-Dimensional Arrays Instead of using 50 int variables, declare a single array which holds 50 int values. To declare an array for 50 int values, we use the following syntax: int list[50]; This creates an int array called list of size 50: list CSE1222: Lecture 13 The Ohio State University

The Ohio State University reverse.cpp ... const int ARRAY_SIZE(5); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements cout << "Enter list of " << ARRAY_SIZE << " integers: "; for (int i = 0; i < ARRAY_SIZE; i++) { cin >> list[i]; } cout << "Reverse list: "; for (int i = ARRAY_SIZE-1; i >= 0; i--) cout << list[i] << " "; cout << endl; CSE1222: Lecture 13 The Ohio State University

The Ohio State University ... const int ARRAY_SIZE(5); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements cout << "Enter list of " << ARRAY_SIZE << " integers: "; for (int i = 0; i < ARRAY_SIZE; i++) { cin >> list[i]; } cout << "Reverse list: "; for (int i = ARRAY_SIZE-1; i >= 0; i--) cout << list[i] << " "; cout << endl; > reverse.exe Enter list of 5 integers: 1 2 3 4 5 Reverse list: 5 4 3 2 1 CSE1222: Lecture 13 The Ohio State University

One-Dimensional Arrays (2) Examples of array declarations: char name[40]; // 40 characters double celsius[90]; // 90 doubles bool flag[1000]; // 1000 true/false values int list[50]; // 50 integers list Note: Arrays are numbered starting at 0. The last element in array list of size 50 is list[49]. CSE1222: Lecture 13 The Ohio State University

Other array declarations Use const int variables to declare arrays: const int CELSIUS_ARRAY_SIZE(90); double celsius[CELSIUS_ARRAY_SIZE]; // 90 doubles const int MAX_LIST_LENGTH(50); int list[MAX_LIST_LENGTH]; // 50 integers CSE1222: Lecture 13 The Ohio State University

The Ohio State University Array Indices The list array from the the previous slide holds 50 integers. list[0] refers to the first element in the array. list[1] is the second element. list[2] is the third element. … list[49] is the fiftieth element. CSE1222: Lecture 13 The Ohio State University

The Ohio State University Using Array Variables Using array variables: list[0] = 77; // assigns 77 to the first // element in array list list[1] = list[0]; list[2] = list[1] + 3; // assigns 80 to list[2] int i = 3; list[2*i] = list[i-1] - list[i-2]; // assigns 3 to list[6] CSE1222: Lecture 13 The Ohio State University

The Ohio State University More array indices list[2*i] = list[i-1] - list[i-2]; The array index can be specified using variables or expressions, but you must be careful of two things: The variable or expression evaluates to an integer The value is in the range of the array. In the list array from the previous slide, the index range is something between 0 and 49. CSE1222: Lecture 13 The Ohio State University

Using a loop with arrays Arrays and for loops go hand-in-hand. Consider the following code: const int SIZE(5); int a[SIZE]; int b[SIZE]; // Note i = 0 and i < SIZE for (int i = 0; i < SIZE; ++i) { a[i] = 10; b[i] = 10*i; } //What does this do? CSE1222: Lecture 13 The Ohio State University

The Ohio State University aboveAverage.cpp // print out above average temperatures ... int main { const int TEMP_SIZE(6); double temp[TEMP_SIZE]; // array of TEMP_SIZE elements double sum(0.0), average(0.0); // input temperatures cout << "Enter the temperature for the last " << TEMP_SIZE << " days: " << endl; for (int i = 0; i < TEMP_SIZE; i++) cin >> temp[i]; } CSE1222: Lecture 13 The Ohio State University

aboveAverage.cpp (cont.) // compute the sum sum = 0.0; for (int i = 0; i < TEMP_SIZE; i++) { sum = sum + temp[i]; } // compute the average average = sum/TEMP_SIZE; // output above average temperatures cout << "Average temperature = " << average << endl; cout << "Above average temperatures: "; if (temp[i] > average) { cout << temp[i] << " "; } cout << endl; CSE1222: Lecture 13 The Ohio State University

aboveAverage.cpp (cont.) ... // output above average temperatures cout << "Average temperature = " << average << endl; cout << "Above average temperatures: "; for (int i = 0; i < TEMP_SIZE; i++) { if (temp[i] > average) { cout << temp[i] << " "; } } cout << endl; > aboveAverage.exe Enter the temperature for the last 6 days: 10 20 30 40 50 60 Average temperature = 35 Above average temperatures: 40 50 60 CSE1222: Lecture 13 The Ohio State University

aboveAverage.cpp (cont.) ... // output above average temperatures cout << "Average temperature = " << average << endl; cout << "Above average temperatures: "; for (int i = 0; i < TEMP_SIZE; i++) { if (temp[i] > average) { cout << temp[i] << " "; } } cout << endl; > aboveAverage.exe Enter the temperature for the last 6 days: 20 25 30 35 40 105 Average temperature = 42.5 Above average temperatures: 105 CSE1222: Lecture 13 The Ohio State University

aboveAverage.cpp (cont.) ... // output above average temperatures cout << "Average temperature = " << average << endl; cout << "Above average temperatures: "; for (int i = 0; i < TEMP_SIZE; i++) { if (temp[i] > average) { cout << temp[i] << " "; } } cout << endl; > aboveAverage.exe Enter the temperature for the last 6 days: 62 65 60 54 22 58 Average temperature = 53.5 Above average temperatures: 62 65 60 54 58 CSE1222: Lecture 13 The Ohio State University

logTableUnsafe.cpp (Unsafe) ... const int TABLE_SIZE(10); double log_table[TABLE_SIZE]; // array of TABLE_SIZE elements int n; cout << "Enter number of integers: "; cin >> n; for (int i = 0; i < n; i++) { log_table[i] = log(double(i+1)); } cout << "log(" << i+1 << ") = " << log_table[i] << endl; CSE1222: Lecture 13 The Ohio State University

logTableUnsafe.cpp (Unsafe) > logTableUnsafe.exe Enter number of integers: 5 log(1) = 0 log(2) = 0.693147 log(3) = 1.09861 log(4) = 1.38629 log(5) = 1.60944 CSE1222: Lecture 13 The Ohio State University

The Ohio State University Why is this unsafe? ... const int TABLE_SIZE(10); double log_table[TABLE_SIZE]; // array of TABLE_SIZE elements int n; cout << "Enter number of integers: "; cin >> n; for (int i = 0; i < n; i++) { log_table[i] = log(double(i+1)); } cout << "log(" << i+1 << ") = " << log_table[i] << endl; CSE1222: Lecture 13 The Ohio State University

The Ohio State University logTable.cpp ... const int TABLE_SIZE(10); double log_table[TABLE_SIZE]; // array of TABLE_SIZE elements int n; cout << "Enter number of integers: "; cin >> n; while (n > TABLE_SIZE) { cout << "Input error.“; cout << " Input must be less than or equal to " << TABLE_SIZE << "." << endl; } CSE1222: Lecture 13 The Ohio State University

The Ohio State University logTable.cpp (cont.) for (int i = 0; i < n; i++) { log_table[i] = log(double(i+1)); } cout << "log(" << i+1 << ") = " << log_table[i] << endl; return 0; CSE1222: Lecture 13 The Ohio State University

The Ohio State University reverse2.cpp ... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(0); cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0 && num < ARRAY_SIZE) { list[num] = x; num++; } cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; CSE1222: Lecture 13 The Ohio State University

The Ohio State University const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements ... cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0 && num < ARRAY_SIZE) { list[num] = x; num++; } cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; > reverse2.exe Enter list of non-zero integers (end list with 0): 1 2 3 -3 -2 -1 0 Reverse list: -1 -2 -3 3 2 1 CSE1222: Lecture 13 The Ohio State University

The Ohio State University const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements ... cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0 && num < ARRAY_SIZE) { list[num] = x; num++; } cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; > reverse2.exe Enter list of non-zero integers (end list with 0): -3 -2 -1 0 1 2 3 0 Reverse list: -1 -2 -3 CSE1222: Lecture 13 The Ohio State University

The Ohio State University const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements ... cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0 && num < ARRAY_SIZE) { list[num] = x; num++; } cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; > reverse2.exe Enter list of non-zero integers (end list with 0): 0 Reverse list: CSE1222: Lecture 13 The Ohio State University

What’s wrong with this program? ... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(0); cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0) { list[num] = x; num++; } cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; CSE1222: Lecture 13 The Ohio State University

What’s wrong with this program? ... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(0); cout << "Enter list of non-zero integers (ending with 0): "; cin >> x; num = 0; while (x != 0 && n <= ARRAY_SIZE) { list[num] = x; num++; } cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; CSE1222: Lecture 13 The Ohio State University

What’s wrong with this program? ... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(1); cout << "Enter list of non-zero integers (ending with 0): "; num = 0; while (x != 0 && n < ARRAY_SIZE) { list[num] = x; num++; cin >> x; } cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; CSE1222: Lecture 13 The Ohio State University

The Ohio State University const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(1); cout << "Enter list of non-zero integers (ending with 0): "; num = 0; while (x != 0 && num < ARRAY_SIZE) { list[num] = x; num++; cin >> x; } ... cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; > reverse2Error3.exe Enter list of non-zero integers (end list with 0): 5 6 7 0 Reverse list: 7 6 5 1 CSE1222: Lecture 13 The Ohio State University

What’s wrong with this program? ... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(1); cout << "Enter list of non-zero integers (ending with 0): "; num = 0; cin >> x; while (x != 0 && n < ARRAY_SIZE) { list[num] = x; num++; } cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; CSE1222: Lecture 13 The Ohio State University

The Ohio State University const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(0); cout << "Enter list of non-zero integers (ending with 0): "; num = 0; while (x != 0 && num < ARRAY_SIZE) { cin >> x; list[num] = x; num++; } ... cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; > reverse2Error4.exe Enter list of non-zero integers (end list with 0): 5 6 7 0 Reverse list: 0 7 6 CSE1222: Lecture 13 The Ohio State University

What’s wrong with this program? ... const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(1); cout << "Enter list of non-zero integers (ending with 0): "; num = 0; while (x != 0 && n < ARRAY_SIZE) { cin >> x; list[num] = x; num++; } cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; CSE1222: Lecture 13 The Ohio State University

The Ohio State University const int ARRAY_SIZE(100); int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements int num(0); int x(1); cout << "Enter list of non-zero integers (ending with 0): "; num = 0; while (x != 0 && num < ARRAY_SIZE) { cin >> x; list[num] = x; num++; } ... cout << "Reverse list: "; for (int i = num-1; i >= 0; i--) { cout << list[i] << " "; } cout << endl; > reverse2Error5.exe Enter list of non-zero integers (end list with 0): 5 6 7 0 Reverse list: 0 7 6 5 CSE1222: Lecture 13 The Ohio State University

The Ohio State University Array Initialization Arrays are initialized like scalar variables, except the list of values are placed in braces. For example: int volts[5] = {2, 9, 100, 34, 27}; char grades[3] = {‘a’, ‘c’, ‘b’}; Initialization of large arrays can be split into 2 rows: double states[10] = {5.4, 3.8, 3.4, 10.6, 9.2, 1.8, 10.3, 14.0, 2.3, 1.4}; CSE1222: Lecture 13 The Ohio State University

Array initialization (2) You do not have to initialize every element of an array: /* initializes hits[0], hits[1], and hits[2] to the values indicated; all the rest are set to 0 */ int hits[6] = {133, 25, 10001}; The size of the array may be omitted if you initialized all of its values at declaration: /* grades has three elements */ int grades[] = {79, 90, 81}; /* same as above */ int grades[3] = {79, 90, 81}; CSE1222: Lecture 13 The Ohio State University

Linear Search Algorithm Array space[] = {7, 3, 6, 25, 3, 2, 75, 3, 5, 6}; Read input key; Find location of key in array space[]; If key is in array space[], print: “Found {key} at location {location}.” If key is not found, print: “Sorry, we did not find {key}”. CSE1222: Lecture 13 The Ohio State University

The Ohio State University linearSearch.cpp . . . int main() { const int SIZE(10); // array size int key(0); // search key (search for key) bool found(false); // flag for linear search // search space (does not need to be in any order) int space[SIZE] = {7, 3, 6, 25, 3, 2, 75, 3, 5, 6}; // get search key from user cout << "Search for: "; cin >> key; CSE1222: Lecture 13 The Ohio State University

The Ohio State University linearSearch.cpp . . . for (int i = 0; i < SIZE; i++) { if (space[i] == key) { // found search key at location i cout << "Found " << key << " at location " << i<< endl; found = true; } if (!found) cout << "Sorry, we did not find " << key << endl; CSE1222: Lecture 13 The Ohio State University

The Ohio State University ... int space[SIZE] = {7, 3, 6, 25, 3, 2, 75, 3, 5, 6}; for (int i = 0; i < SIZE; i++) { if (space[i] == key) { // found search key at location i cout << "Found " << key << " at location " << i<< endl; found = true; } > linearSearch.exe Search for: 2 Found 2 at location 5 Search for: 8 Sorry, we did not find 8 What about 6? What about 3? CSE1222: Lecture 13 The Ohio State University

Search for Duplicates Algorithm Read in input list; for each element x in the list do: for each element y following x in the list do: If (x == y), then print: “Duplicate entry {location of x} = Entry {location of y} = y”; CSE1222: Lecture 13 The Ohio State University

The Ohio State University duplicate.cpp // print duplicate entries in input list #include <iostream> using namespace std; int main() { const int SIZE(10); // array size int list[SIZE]; cout << "Enter list of " << SIZE << " integers: "; for (int i = 0; i < SIZE; i++) cin >> list[i]; } CSE1222: Lecture 13 The Ohio State University

The Ohio State University duplicate.cpp (cont.) for (int i = 0; i < SIZE; i++) { for (int j = i+1; j < SIZE; j++) if (list[i] == list[j]) cout << "Duplicate entry " << i << " = Entry " << j << " = " << list[j] << endl; } return 0; CSE1222: Lecture 13 The Ohio State University

The Ohio State University ... for (int i = 1; i < SIZE; i++) { for (int j = i+1; j < SIZE; j++) if (list[i] == list[j]) cout << "Duplicate entry " << i << " = Entry " << j << " = " << list[j] << endl; } What does this output on input: 7 5 3 8 5 6 8 1 5 2? CSE1222: Lecture 13 The Ohio State University

Duplicates Algorithm: Version 2 Read in input list; for each element x in the list do: found_duplicate ← false; for each element y following x in the list do: If ((x = y) and (found_duplicate = false)), then Print: “Duplicate entry {location of x} = Entry {location of y} = y”; found_duplicate ← true; CSE1222: Lecture 13 The Ohio State University

The Ohio State University ... for (int i = 1; i < SIZE; i++) { found_duplicate = false; for (int j = i+1; j < SIZE; j++) if (list[i] == list[j] && !found_duplicate) cout << "Duplicate entry " << i << " = Entry " << j << " = " << list[j] << endl; found_duplicate = true; } What does this output on input: 7 5 3 8 5 6 8 1 5 2? CSE1222: Lecture 13 The Ohio State University

Common Programming Errors Addressing indices that are out of bounds of the array range. This will run-time crash or at the very least a logical error. Be careful especially when using expressions to compute the indices. Remember, indexing starts with 0, not 1!!! Forgetting to declare the array (either altogether or forgetting the []) Forgetting to initialize an array. Some compilers set everything to zero, some do not. CSE1222: Lecture 13 The Ohio State University

The Ohio State University Binary Search CSE1222: Lecture 13 The Ohio State University

Linear Search Algorithm Array space[] = {7, 3, 6, 25, 3, 2, 75, 3, 5, 6}; Read input key; Find the first location of key in array space[]; If key is in array space[], print: “Found {key} at location {location}.” If key is not found, print: “Sorry, we did not find {key}”. CSE1222: Lecture 13 The Ohio State University

The Ohio State University Binary Seach Array list[] = {2, 3, 5, 6, 6, 7, 10, 12, 25, 75}; Given a list in sorted order and a key: Find a location of the key in the list. Guess a number between 1 and 100. CSE1222: Lecture 13 The Ohio State University

Binary Search Algorithm Array list[] = (list[0], list[1], list[2], …, list[9]) Input: key Compare key to list[5]; If (key = list[5]), then “FOUND KEY!”; If (key < list[5]), then search (list[0], list[1], …, list[4]) If (key > list[5]), then search (list[6], list[7], …, list[9]) CSE1222: Lecture 13 The Ohio State University

Search (list[0], list[1], …, list[4]) (list[0], list[1], list[2], …, list[4]) Compare key to list[2]; If (key = list[2]), then “FOUND KEY!”; If (key < list[2]), then search (list[0], list[1]) If (key > list[2]), then search (list[3], list[4]) CSE1222: Lecture 13 The Ohio State University

Binary Search Algorithm (list[0], list[1], list[2], …, list[N-1]) left ← 0; right ← N-1; While (key is not found) do midpoint ← (left + right)/2; If (key = list[midpoint]), then “FOUND KEY!”; If (key < list[midpoint]), then right ← midpoint-1; If (key > list[midpoint]), then left ← midpoint+1; If (right < left), then quit search; (key is not in list) CSE1222: Lecture 13 The Ohio State University

Binary Search Algorithm (list[0], list[1], list[2], …, list[N-1]) left ← 0; right ← N-1; While (key is not found and left ≤ right) do midpoint ← (left + right)/2; If (key = list[midpoint]), then “FOUND KEY!”; If (key < list[midpoint]), then right ← midpoint-1; If (key > list[midpoint]), then left ← midpoint+1; CSE1222: Lecture 13 The Ohio State University

The Ohio State University binarySearch.cpp int main() { const int SIZE(10); // array size const key(0); // search for key int left(0), right(0), midpoint(0); // index array bool found(false); // flag found key // this is an ORDERED LIST int list[SIZE] = {2, 3, 5, 6, 6, 7, 10, 12, 25, 75}; // get search key from user cout << "Search for: "; cin >> key; ... CSE1222: Lecture 13 The Ohio State University

The Ohio State University binarySearch.cpp ... left = 0; right = SIZE - 1; while (left <= right && !found) { midpoint = (left + right) / 2; // the floor (int division) if (key == list[midpoint]) { found = true; } // key is at midpoint else if (key < list[midpoint]) { right = midpoint - 1; } // consider left half of list else { left = midpoint + 1; } // consider right half of list } if (found) { cout << "Found " << key << " at location " << midpoint << endl; { cout << "Sorry, we did not find " << key << endl; } CSE1222: Lecture 13 The Ohio State University