Problem Solving and Algorithms Chapter 7 Problem Solving and Algorithms
Chapter Goals The Computer Problem Solving Process Top-Down Design What is an Algorithm Common Programming Control Structures Selection Repetition Sub-programs
Chapter Goals Arrays of Data Unsorted arrays and sorted arrays Recursion and recursive algorithms
Chapter Goals Common algorithms and their hand-simulatiion In Particular… Bubblesort algorithm Quicksort algorithm Sequential Search algorithm Binary Search algorithm
Problem Solving
Computer Problem-Solving aka “Software Development Lifecycle” Analysis and Specification Phase Analyze Specification Algorithm Development Phase Develop algorithm Test algorithm Implementation Phase Code algorithm Maintenance Phase Use Maintain Can you name a recurring theme?
Phase Interactions Should we add another arrow? (What happens Problem Should we add another arrow? (What happens if the problem is revised?)
Solutions are in the form of Algorithms For computer science, our “answers” are algorithms
Algorithms Algorithm A set of unambiguous instructions for solving a problem Abstract Step An algorithmic step containing unspecified details Concrete Step An algorithm step in which all details are specified (a step that a computer will understand)
Developing an Algorithm Two methodologies are used to develop solutions Top-down design focuses on the tasks to be done Object-oriented design focuses on the data involved in the solution (More in Chapter 9)
Top-Down V Object Oriented Question: Which methodology is Best? Answer: Both are used Depends on the level of abstraction
Top-Down Methodology Start with Main Module (representing the entire problem) Break into a list of steps Each step becomes a sub-module Repeat for Each Sub-module Continue until all steps are CONCRETE Process ends when all steps are concrete
Top-Down Design Process continues until every step is concrete Name of (sub)problem at one level becomes a module at next lower level
Top-Down Wedding Planning
Algorithm Control Structures
Control Structures Control structure A construct that determines the order in which instructions are executed Mainly: Selection aka “Decisions” Iteration aka “Looping”
Selection Statements Flow of control of if statement
Algorithm with Selection Problem: Write the appropriate dress for a given temperature. Write "Enter temperature" Read temperature Determine Dress Which statements are concrete? Which statements are abstract? 18 18
Algorithm with Selection Determine Dress IF (temperature > 90) Write “Texas weather: wear shorts” ELSE IF (temperature > 70) Write “Ideal weather: short sleeves are fine” ELSE IF (temperature > 50) Write “A little chilly: wear a light jacket” ELSE IF (temperature > 32) Write “Philadelphia weather: wear a heavy coat” ELSE Write “Stay inside” 19 19
Looping Statements Flow of control of while statement
Looping in Psuedocode A count-controlled loop (Factorial of N) Set fact to 1 Set count to 1 Write "Please enter a number: " Read in N While (count <= N) Set fact to fact * count Increment count Write N + “Factorial is " + fact
Actual Code!! Now, with A count-controlled loop (Factorial of N) cout << "Please enter a number: "; cin >> N; while(count <= N){ fact = fact * count; count = count + 1; } cout << N << " Factorial is: " << fact;
Arrays
Arrays A set of homogeneous (same type) data elements requires a count of how many elements Data elements are accessed via an index: list[0] to list[count-1]
An Unsorted Array
Searching
Sequential Search Algorithm Look at every item until the item is found In More Detail… Look at the first item If it matches, we are done Look at the next item Repeat until the end of the list
Sequential Search Algorithm STRUCTURED Set Position to 0 Set found to FALSE WHILE (position < length AND NOT found ) IF (numbers [position] equals searchitem) Set Found to TRUE ELSE Set position to position + 1
Sorted Arrays A Sorting Algorithm puts array elements in either ascending or descending order. Pro: Sorting makes it easier to searches Con: Sorting takes time to do
A Sorted Array
Binary Search Algorithm A classic searching algorithm More efficient than sequential search But, data must be sorted already Binary search steps: Begin at the middle, eliminate half of the items, repeat on the remaining half
Binary Search - STRUCTURED Set first to 0 Set last to length-1 Set found to FALSE WHILE (first <= last AND NOT found) Set middle to (first + last)/ 2 IF (item equals data[middle])) Set found to TRUE ELSE IF (item < data[middle]) Set last to middle – 1 Set first to middle + 1 RETURN found
Binary Search lama Figure 7.10 Trace of the binary search
Binary Search Table 7.1 Average Number of Comparisons
Sorting
Sorting Sorting Arranging items in a collection so that they are in order Sorting algorithms Algorithms that put items in order
Bubble Sort Bubble Sort Algoritm: Compare a pair of items Put the smaller item on top Repeat the above for the next pair of items Repeat the entire process until the list is sorted
Bubble Sort
Bubble Sort - STRUCTURED Set firstUnsorted to 0 Set index to firstUnsorted + 1 Set swap to TRUE WHILE (index < length AND swap) Set swap to FALSE “Bubble up” the smallest item in unsorted part Set firstUnsorted to firstUnsorted + 1
Bubble Sort - STRUCTURED Bubble up Set index to length – 1 WHILE (index > firstUnsorted + 1) IF (data[index] < data[index – 1]) Swap data[index] and data[index – 1] Set swap to TRUE Set index to index - 1 40 40
Subprograms
Subprograms YAY Abstraction!! We can name a section of code and use it in another part of a program We can use this “block of code” as an abstraction YAY Abstraction!!
Subprogram Statements Figure 7.14 Subprogram flow of control
Subprograms in the Wedding “Ceremony” could be a written as a subprogram Abstraction helps us be organized subprogram
Subprograms and Data We can send data to/from a subprogram Arguments Data sent to a sub program Return Values Data returned from a subprogram
Subprogram Statements
Recursion
Recursive Stuff… Smaller versions repeat…
More Recursive Stuff…
Recursion Recursion The ability of a subprogram to call itself 1) Base case The case to which we have an answer 2) General case Expressing the solution as a smaller version of the problem
Recursion Factorial is the classic example. The factorial of a number is the number times the product of all the numbers between itself and 1. For example: 5! 5! = 5*4*3*2*1 = 120 Or, thinking recursively, 5! = 5*4!
Factorial via Recursion Base case Factorial(1) = 1 General Case Factorial(N) = N * Factorial(N-1)
Recursive Factorial Algorithm Write “Enter n” Read n Set result to Factorial(n) Write result + “ is the factorial of “ + n Factorial(n) IF (n equals 1) RETURN 1 ELSE RETURN n * Factorial(n-1) 53 53
Actual Code!! Now, with cout << "Please enter a number: "; cin >> n; result = Factorial(n); cout << n << " factorial is: " << result; int Factorial(int n) { if(n == 1) return 1; else return n * Factorial(n -1); } 54 54