Ch 8. Searching and Sorting Arrays Part 1. Definitions of Search and Sort

Similar documents
! Search: find an item in an array, return the. ! Sort: rearrange the items in an array into some. ! There are various methods (algorithms) for

Searching, Sorting & Analysis

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

8.1. Chapter 8: Introduction to Search Algorithms. Linear Search. Linear Search. Linear Search - Example 8/23/2014. Introduction to Search Algorithms

C/C++ Programming Lecture 18 Name:

LECTURE 08 SEARCHING AND SORTING ARRAYS

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself?

Chapter 10 - Notes Applications of Arrays

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself? contains a reference to itself.

The University Of Michigan. EECS402 Lecture 07. Andrew M. Morgan. Sorting Arrays. Element Order Of Arrays

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Ch 6. Functions. Example: function calls function

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

Introduction to the Analysis of Algorithms. Algorithm

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Search Lesson Outline

Recursion. ! When the initial copy finishes executing, it returns to the part of the program that made the initial call to the function.

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Topics Applications Most Common Methods Serial Search Binary Search Search by Hashing (next lecture) Run-Time Analysis Average-time analysis Time anal

What did we talk about last time? Finished hunters and prey Class variables Constants Class constants Started Big Oh notation

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

Algorithm Complexity Analysis: Big-O Notation (Chapter 10.4) Dr. Yingwu Zhu

CS 231 Data Structures and Algorithms Fall Algorithm Analysis Lecture 16 October 10, Prof. Zadia Codabux

do { statements } while (condition);

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

[ 11.2, 11.3, 11.4] Analysis of Algorithms. Complexity of Algorithms. 400 lecture note # Overview

Search Algorithms. Linear Search Binary Search

Programming 1. Lecture 6 Structured data types. Arrays

QuickSort. CIS 15 : Spring 2007

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

ECE 2400 Computer Systems Programming Fall 2018 Topic 8: Complexity Analysis

CS240 Fall Mike Lam, Professor. Algorithm Analysis

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

Functions, Arrays & Structs

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

Sum this up for me. Let s write a method to calculate the sum from 1 to some n. Gauss also has a way of solving this. Which one is more efficient?

Algorithm Analysis. Performance Factors

Increment and the While. Class 15

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

ALGORITHM ANALYSIS. cs2420 Introduction to Algorithms and Data Structures Spring 2015

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1

MPATE-GE 2618: C Programming for Music Technology. Unit 4.2

pointers + memory double x; string a; int x; main overhead int y; main overhead

Ch. 17: Linked Lists. Introduction to Linked Lists

Measuring algorithm efficiency

Data Structures Lecture 3 Order Notation and Recursion

Recursion. Example R1

Algorithms. Algorithms 1.4 ANALYSIS OF ALGORITHMS

The American University in Cairo Department of Computer Science & Engineeringt CSCI &09 Dr. KHALIL Exam-I Fall 2009

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Lab 14 SERACHI G Dr. John P. Abraham

VARIABLES & ASSIGNMENTS

Linked List using a Sentinel

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Algorithm Analysis. Big Oh

Integer Data Types. Data Type. Data Types. int, short int, long int

Heaps. A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience)

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

To explain growth rates and why constants and nondominating terms can be ignored in the estimation

CS 215 Lecture 17 Linked lists and time complexities

Building Java Programs Chapter 13

CSC 273 Data Structures

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Faster Sorting Methods

CS 132 Exam #1 - Study Suggestions

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Lecture 23: Pointer Arithmetic

Algorithm Analysis. CENG 707 Data Structures and Algorithms

SORTING AND SEARCHING

CSE 373 APRIL 3 RD ALGORITHM ANALYSIS

CSCI 261 Computer Science II

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

ECE 122. Engineering Problem Solving Using Java

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Algorithms A Look At Efficiency

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

Search,Sort,Recursion

Unit 7. 'while' Loops

10/11/2013. Chapter 3. Objectives. Objectives (continued) Introduction. Attributes of Algorithms. Introduction. The Efficiency of Algorithms

To become familiar with array manipulation, searching, and sorting.

Recall from Last Time: Big-Oh Notation

CS2141 Software Development using C/C++ C++ Basics

CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation

Classic Data Structures Introduction UNIT I

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt

Problem Solving: Storyboards for User Interaction

ASYMPTOTIC COMPLEXITY

Multiple Choice Questions (20 questions * 5 points per question = 100 points)

Programming Language. Functions. Eng. Anis Nazer First Semester

Today in CS161. Lecture #7. Learn about. Rewrite our First Program. Create new Graphics Demos. If and else statements. Using if and else statements

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

CS 311 Data Structures and Algorithms, Spring 2009 Midterm Exam Solutions. The Midterm Exam was given in class on Wednesday, March 18, 2009.

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return

Transcription:

Ch 8. Searching and Sorting Arrays Part 1 CS 2308 Fall 2011 Jill Seaman Lecture 1 1 Definitions of Search and Sort! Search: find an item in an array, return the index to the item, or -1 if not found.! Sort: rearrange the items in an array into some order (smallest to biggest, alphabetical order, etc.).! There are various methods (algorithms) for carrying out these common tasks.! Goal: compare the efficiency of the algorithms. 2

Linear Search! Very simple method.! Compare first element to target value, if not found then compare second element to target value...! Repeat until target value is found (return its index) or we run out of items (return -1). 3 Linear Search in C++ int searchlist (int list[], int numelems, int value) { int index=0; int position = -1; bool found = false; //index to process array //record position of value //flag, true when value is found while (index < numelems &&!found) { if (list[index] == value) //found the value! { found = true; position = index; index++; return position; //set the flag //record which item //increment loop index 4

Questions! Why not a for loop?! Why return -1 for not found? 5 Program using Linear Search #include <iostream> using namespace std; int searchlist(int[], int, int); const int SIZE=5; int main() { int idnums[size] = {871, 750, 988, 100, 822; int results, id; cout << Enter the employee ID to search for: ; cin >> id; results = searchlist(idnums, SIZE, id); if (results == -1) { cout << That id number is not registered\n ; else { cout << That id number is found at location ; cout << results+1 << endl; return 0; 6

Efficiency of Search Algorithms! We measure efficiency of algorithms in terms of number of main steps required to finish.! For search algorithms, the main step is comparing array element to the target value.! Number of steps depends on: " size of input array " whether or not value is in array " where the value is in the array 7 Efficiency of Linear Search N=50,000 In terms of N Best Case: 1 1 Average Case: 25,000 N/2 Worst Case: 50,000 N *N is the number of elements in the array Note: if we search for items not in the array, the average case will increase. 8

Binary Search! Works only for SORTED arrays! Compare target value to middle element in array. " if equal, then return index " if less than middle elem, search in first half " if greater than middle elem, search in last half! If search list is narrowed down to 1 elem, and it is not equal to target value, return -1! Divide and conquer style algorithm 9 Binary Search Algorithm The algorithm described in pseudocode: location = -1; first = 0; last = number of items in list minus 1; while ((number of items left to search >= 1) and (target not found)) middle = pos of middle item, ½-way between first and last if (item at middle position is target) target found location = middle else if (target < middle item) search lower half of list next: last = middle - 1; else search upper half of list next: end while first = middle + 1; 10

Binary Search in C++ int binarysearch (int array[], int numelems, int value) { int first = 0, //index to first elem last = numelems 1, //index to last elem middle, //index of middle elem position = -1; //index of target value bool found = false; //flag while (!found && first <= last) { middle = (first + last) /2; //calculate midpoint if (array[middle] == value) { found = true; position = middle; else if (array[middle] > value) { last = middle 1; //search lower half else { fisrt = middle + 1; //search upper half return position; 11 Program using Binary Search #include <iostream> using namespace std; int binarysearch(int[], int, int); const int SIZE=5; int main() { int idnums[size] = {100, 750, 822, 871, 988; int results, id; cout << Enter the employee ID to search for: ; cin >> id; results = binarysearch(idnums, SIZE, id); if (results == -1) { cout << That id number is not registered\n ; else { cout << That id number is found at location ; cout << results+1 << endl; return 0; 12

Efficiency of Binary Search Calculate worst case for N=1024 Num items left to search Comparisons so far 1024 0 512 1 256 2 128 3 64 4 32 5 16 6 8 7 4 8 2 9 1 10 If 1024 = 2 10 then what does 10 =? 13 Efficiency of Binary Search N=50,000 In terms of N Best Case: 1 1 Worst Case: 15.6 log 2 N *N is the number of elements in the array Is log 2 N (binary search) better than N (linear search)? [Is it really fair to compare these two algorithms?] 14

Is Log 2 N better than N? Compare values of N/2, N, and Log 2 N as N increases: N N/2 Log 2 N 5 2.5 2.3 50 25 5.6 500 250 9 5,000 2,500 12.3 50,000 25,000 15.6 observation: n/2 is growing much faster than log n! slower growing is more efficient. 15 Classifications of (math) functions! Constant y=b O(1)! Logarithmic y=log b (x) O(log n)! Linear y=ax+b O(n)! Linearithmic y=x log b (x) O(n log n)! Quadratic y=ax2 +bx+c O(n 2 )! Exponential y=b x O(2 x ) Last column is big Oh notation used in CS 16

Some graphs 17 Some more graphs 18

Efficiency of Algorithms! To classify efficiency of an algorithm: " Express time as a function of input " Determine which classification the function fits into.! Nearer to the top is slower growth, and more efficient (constant is better than logarithmic, etc.) 19