Data Types. Operators, Assignment, Output and Return Statements

Similar documents
Sorting. Task Description. Selection Sort. Should we worry about speed?

Component 02. Algorithms and programming. Sorting Algorithms and Searching Algorithms. Matthew Robinson

ECE 2574: Data Structures and Algorithms - Basic Sorting Algorithms. C. L. Wyatt

Sorting and Searching

Faster Sorting Methods

! 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.

Sorting. Order in the court! sorting 1

Objectives. Chapter 23 Sorting. Why study sorting? What data to sort? Insertion Sort. CS1: Java Programming Colorado State University

About this exam review

Sorting. Order in the court! sorting 1

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

Sorting and Searching Algorithms

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

CS115 Principles of Computer Science

9/10/12. Outline. Part 5. Computational Complexity (2) Examples. (revisit) Properties of Growth-rate functions(1/3)

CSCI 261 Computer Science II

! 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.

COMP 250. Lecture 7. Sorting a List: bubble sort selection sort insertion sort. Sept. 22, 2017

Lecture 7: Searching and Sorting Algorithms

CmpSci 187: Programming with Data Structures Spring 2015

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

Measuring algorithm efficiency

Chapter 6 Single-dimensional Arrays

! 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.

2/14/13. Outline. Part 5. Computational Complexity (2) Examples. (revisit) Properties of Growth-rate functions(1/3)

A+ Computer Science. SORTING & Searching

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

10/21/ Linear Search The linearsearch Algorithm Binary Search The binarysearch Algorithm

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

Sorting Algorithms. + Analysis of the Sorting Algorithms

Introduction to Computer Science Midterm 3 Fall, Points

Data Structures and Algorithms for Engineers

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place?

Chapter 10 - Notes Applications of Arrays

Searching Elements in an Array: Linear and Binary Search. Spring Semester 2007 Programming and Data Structure 1

Opening Problem EXAMPLE. 1. Read one hundred numbers, 2. compute their average, and 3. find out how many numbers are above the average.

Sorting. Weiss chapter , 8.6

CS1150 Principles of Computer Science Arrays

for (int outercounter = nums.length - 1; outercounter > 0 && swappedthatturn; outercounter --

Unit-2 Divide and conquer 2016

Chapter 7: Single-Dimensional Arrays. Declaring Array Variables. Creating Arrays. Declaring and Creating in One Step.

Searching and Sorting Chapter 18. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

Sorting. CSE 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation. CSE143 Au

CS 12 Fall 2003 Solutions for mid-term exam #2

CS1 Lecture 30 Apr. 2, 2018

Sorting. CSC 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation CSC Picture

Bubble sort starts with very first two elements, comparing them to check which one is greater.

Algorithm Analysis. Performance Factors

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

CS125 : Introduction to Computer Science. Lecture Notes #40 Advanced Sorting Analysis. c 2005, 2004 Jason Zych

Objectives of the lesson

Algorithms and Applications

Overview of Sorting Algorithms

Better sorting algorithms (Weiss chapter )

KF5008 Algorithm Efficiency; Sorting and Searching Algorithms;

Topic 17 Fast Sorting

Chapter 10 Sorting and Searching Algorithms

Sorting Pearson Education, Inc. All rights reserved.

Classic Data Structures Introduction UNIT I

Chapter 10. Sorting and Searching Algorithms. Fall 2017 CISC2200 Yanjun Li 1. Sorting. Given a set (container) of n elements

Algorithms. Chapter 8. Objectives After studying this chapter, students should be able to:

CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Signature: Question # Out Of Marks Marker Total

Searching and Sorting

Arrays. Week 4. Assylbek Jumagaliyev

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

Key question: how do we pick a good pivot (and what makes a good pivot in the first place)?

Unit 10: Sorting/Searching/Recursion

Mergesort again. 1. Split the list into two equal parts

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

CS 61B Summer 2005 (Porter) Midterm 2 July 21, SOLUTIONS. Do not open until told to begin

We can use a max-heap to sort data.

COMP1511 focuses on writing programs. Effciency is also important. Often need to consider:

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Lexical Considerations

Searching for Information. A Simple Method for Searching. Simple Searching. Class #21: Searching/Sorting I

COMP2012H Spring 2014 Dekai Wu. Sorting. (more on sorting algorithms: mergesort, quicksort, heapsort)

Summer Final Exam Review Session August 5, 2009

UE Algorithmen und Datenstrukturen 1 UE Praktische Informatik 1. Übung 9. Sorting

Introduction to Programming Using Java (98-388)

Chapter 3: Operators, Expressions and Type Conversion

CS 310 Advanced Data Structures and Algorithms

UNIT 7. SEARCH, SORT AND MERGE

QuickSort

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS

Copyright 2012 by Pearson Education, Inc. All Rights Reserved.

Exam Datastrukturer. DIT960 / DIT961, VT-18 Göteborgs Universitet, CSE

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

Unit Outline. Comparing Sorting Algorithms Heapsort Mergesort Quicksort More Comparisons Complexity of Sorting 2 / 33

Data Structures and Algorithms Running time, Divide and Conquer January 25, 2018

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

ITEC2620 Introduction to Data Structures

Sorted List Matching Problem

Programming II (CS300)

CHAPTER 7 Iris Hui-Ru Jiang Fall 2008

JAVA OPERATORS GENERAL

There are two possible results from a search: either you find the item you are looking for, or you don't.

Reviewing all Topics this term

Outline. Quadratic-Time Sorting. Linearithmic-Time Sorting. Conclusion. Bubble/Shaker Sort Insertion Sort Odd-Even Sort

LECTURE 17. Array Searching and Sorting

Transcription:

Pseudocode Reference Sheet rev 4/17 jbo Note: This document has been developed by WeTeach_CS, and is solely based on current study materials and practice tests provided on the TEA website. An official pseudocode reference page is available in the 241 Preparation Manual. Data Types int x <- 10 boolean ismoving <- true char grade <- 'A' string fruit <- "Apple" float num <- 3.14 An integer variable A Boolean (true or false) variable A character variable A string variable A floating point (decimal) variable Operators, Assignment, Output and Return Statements a expression a <- expression a b * 3 + 2 a <- b * 3 + 2 print k print (k) Evaluates expression and assigns the result to the variable, a right to left operation. Prints the value of k Note: Both print styles are demonstrated in the practice test return 1 + b Returns the sum of 1 and b Page 1

Arithmetic Operators a+b "dog" + "cat" ==> "dogcat" "dog " + "cat" ==> "dog cat" "dog" + 5 + 1.2 ==> "dog51.2" 5 + 1.2 + "dog" ==> "6.2dog" a-b a*b a/b a%b The arithmetic operators +, -, *, / and % perform arithmetic operations on a and b, and work on both integer and floating point values. Concatenation of strings also uses the + operator. For all arithmetic operations, when both operands are integers, the result is an integer. If either or both operands are of type float (a decimal), the result is a float. For example: 4 + 5 results in 9 4 + 5.0 results in 9.0 3 / 2 is 1 3.0 / 2 is 1.5 10 % 6 is 4 6 % 10 is 6 Note: The order of operations is the same as it is for mathematics: Multiplicative operations first (*, /, %) with multiple instances evaluated in order from left to right, and then additive operations (+,-), also evaluated in order from left to right. Relational Operators a == b a b, a!=b, a<>b a < b a > b All of these relational operators are used to test the relationship between two variables, expressions, or values, with a boolean result of true or false. For example, a == b evaluates to true if a and b contain equal values, otherwise it evaluates to false. Here are other examples: Page 2

a b, a>=b a b, a<=b 4 == 5 is false 4 <= 5 is true 4 < 5 is true 4 >= 5 is false 4 > 5 is false 4!= 5 is true Note: There is no evidence of any distinction between primitives and objects in any of the practice test questions or study materials for the test, therefore it will be assumed that any comparison between strings, or any other object data types, will indeed be comparing the contents of the data, and not the memory locations. Logical Operators NOT condition! condition Reverses the value of the boolean expression, becoming true if it is false, or false if it is true. condition1 AND condition2 Evaluates to true if both condition1 and condition2 are true; otherwise evaluates to false. condition1 XOR condition2 Evaluates to true if the conditions are opposite - true AND false, or false AND true If the conditions are the same, it evaluates to false. condition1 OR condition2 Evaluates to true if either or both conditions are true, false if both are false. Note: The order of precedence for the logical operators, should there be expressions with multiple operations, is as they are listed above: NOT, AND, XOR, then OR NAXO for short. Page 3

Operator Precedence The overall order of operator precedence for the certification exam pseudocode system is as follows: 1. Unary (positive +, negative, NOT!) 2. Multiplicative (*, /, %) 3. Additive (+, -) 4. Relational (<, >, <=,, >=, ) 5. Equality (==,!=, <>, ) 6. Logical AND (&&) 7. Logical XOR (^) 8. Logical OR ( ) 9. Assignment (<-, ) Page 4

If and If else Statements if ( condition ) end if The indented statement or group of statements are executed if the Boolean condition evaluates to true, otherwise are skipped over if the condition evaluates to false. if ( condition ) else end if The indented statement or group of statements following the if are executed if the Boolean condition evaluates to true, otherwise the statements following the else are executed. Loop statements for(start; condition true?; step) end for start while (condition true?) The indented statement or group of statements is executed each time the condition is true. The order of execution is rigid - start only once, check the condition, if true, do the action, then step, check, action, step, check, action, step, stop when check is false. The indented statement or group of statements is executed each time the while condition is true. The action and step are both included in the indented statements, and can be listed in any order. start do{ } while (condition true?) The indented statement or group of statements is executed immediately after the do, always executing at least once. The action and step are both included in the indented statements, and can be listed in any order. The statement(s) will be executed again each time the ending while condition is true. Page 5

Method Blocks void grading (char grade) end grading This is a void method (procedure) named grading which accepts a character parameter grade, with no return value procedure coffeetype (string coffee ) end coffeetype int f (int x, int y) end f This is a procedure (void method) named coffeetype which accepts a string parameter coffee, with no return value This is a return method (function) f which accepts two integer variables x and y and returns an integer One and Two Dimensional Arrays int [] list int array list see practice test, question 24 for this notation style declares an array of integers - two different notation styles are demonstrated in the practice test int [] list <- {1,2,-3,4} int [][] grid <- {{-1,2},{3,-4,5}} string [] words <- {"Tom","Dick","Harry"} Arrays declared and instantiated with values float [] nums <- {1.2,-2.9,0.53} Page 6

print list[0] result 1 print list[2] result -3 print grid[0][0] result -1 print grid[1][2] result 5 grid[1][2] <- grid[0][1] + 10 print grid[1][2] result 12 print words[2] result Harry print nums[1] result -2.9 int[] list <- new int[3] list[0] <- 15 list[1] <- -1 list[2] <- 99 print list[2] result 99 list[2] <- -10 print list[2] result -10 list.length result 4 len(list) result 4 grid.length result 2 (2 rows are in the grid) grid[1].length result 3 (3 elements are in row 1 of the grid) len(words) result 3 nums.length result 3 for(int x<-0;x<list.length;x<-x+1) print list[x] Individual array elements accessed This code creates a new integer array with slots for three elements, and then assigns values to those slots. It thens outputs one of the elements, reassigns that slot, and outputs the new value. Here are two ways to return the number of elements in an array structure: Use the length command to report the number of elements contained. Call a method len, which returns the length of the array parameter This for loop outputs all of the elements of the array. Output result: 1 2-3 4 for(int x<-0;x<len(words);x<-x+1) print words[x] Page 7

Output result: Tom Dick Harry for(int r<-0;r<grid.length;r<-r+1) for(int c<-0;c<grid[r].length;c<-c+1) print grid[r][c] Output result: -1 2 3-4 12 int[] list <- new int[3] list[2] <- 4 Assigns the value 4 to the last position of the array Note: 1D and 2D arrays for all data types will follow the same structure and notation as the given examples have shown. Page 8

PARAMETERS Parameter - A value, expression, or variable located inside the parentheses of a method call or method header. Actual Parameter Value, expression, or variable in a method call. Formal Parameter Variable (no literal values or expressions) listed in a method header that receives a value or expression result from an actual parameter in a method or procedure call, and is only in scope during the execution of the method. Parameter Passing - The process in the source code of a program whereby data is passed from one section of the program to another, using method calls that send actual parameters, and method definitions that receive the passed data using formal parameters. Passing by Value - When a parameter is passed by value to a method, any changes made to the formal parameter inside the method DO NOT affect the actual parameter. Passing by Reference - When a parameter is passed by reference, the memory location originally referred to by the actual parameter is passed to the formal parameter, such that any changes made to the object by the formal parameter also affect the original actual parameter. Page 9

Searches Linear Search o A linear search uses a loop process to search for the target item, starting at the front of the list and proceeding through the list, one item at a time, stopping when it either finds the target, or reaches the end of the list. o There are three scenarios for the running time of a Linear Search: Best Case - Constant time O(1) the search target is the first element of the list, or pretty close to the front Average Case Linear time O(N) the item is somewhere in the middle of the list. Even finding the element halfway through the list is still considered Linear time. Worst Case Linear time O(N) the item is at the end of the list, is pretty close to the end of the list, or is not found. o Pseudocode for Linear Search int linearsearch(int[] list, int target) for (int j 0; j < list.length; j j + 1) end for if (list[j] == target) end if return 1 end linearsearch return j //sample client code int[] list {5,7,3,9,4,6} print linearsearch(list,3) print linearsearch(list,6) print linearsearch(list,2) 2 5-1 Page 10

Binary Search o A binary search requires the list to be in sorted order, according to the natural order of the data contained (alpha, numeric, etc.) o It then systematically o looks at the middle of the list to see if that data item matches the target. o If the middle item matches the target, return the position in the list where it was found. o If it does not match, determine which way to continue the search, either to the left of the middle if the target is less than the middle, or to the right if it is greater. o Within the left or right half of the list, it repeats the process: Find the middle of that half Compare it to the target If it matches, return the position of that item, and if not, look left or right o This divide and conquer approach continues until the item is found, or until there are no more data items to examine, at which time the search process ends. o The three scenarios for the running time of a Binary Search are: Best Case - Constant time O(1) the search target is the first middle element of the list Average Case Logarithmic time O(log N) the item is somewhere in the list Worst Case Logarithmic time O(log N) the item is not in the list. o Pseudocode for Binary Search int binarysearch(int[] list, int target) int left 0,right list.length 1 //left at start, right at end while (left <= right) int middle (left + right)/2 //find the middle of the list if (target == list[middle]) return middle else if (target < list[middle]) //if target less than middle right middle 1 else left middle + 1 end if else chain return -1 //target not found end binarysearch //while left and right have not crossed //look left (change right marker to //position one place before the middle) //look right (change left marker to //sample client code int[] list {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20} print binarysearch(list,3) //found in 5 steps middle values of 10, 4, 1, 2 and finally 3 print binarysearch(list,16) //found in 4 steps middle values of 10, 15, 18, 16 print binarysearch(list,21) //middle values of 10, 15, 18, 19, 20 are checked before left and right finally cross, indicating the value is not found. 3 16-1 Page 11

Sorts Selection Sort - Uses a nested loop process (loop within a loop) to select the best data for a particular position, then swap the best data with the value in that place. void selectionsort(pass-by-reference int[] list) for (int k 0;k<list.length-1;k k+1) //k loop starts at zero and stops int best k //one position short of end of list //assume that position k has best value for (int q k+1;q<list.length;q q+1)//q loop searches the rest of if (list[q] < list[best]) end q loop best q swap(list, k, best) end k loop end selectionsort //three step swap process //the list for a better value //if q indicates a better value, //best gets q //swap values at positions k and best void swap (pass-by-reference int[] list, int i, int j) int temp list[i] list[i] list [j] list [j] temp end swap Page 12

Bubble Sort - Uses a nested loop process (loop within a loop) to compare neighboring items and make swaps as neighbors are out of natural order. void bubblesort(pass-by-reference int[] list) boolean done false //assume sorting process is NOT done while(not done) done true //assume sorting process IS done, and list is sorted BUT for (int k 0; k<list.length-1; k k+1) // look through the list anyway to see //if any neighboring elements are out //of order and need to be swapped if (list[k+1] < list[k]) //if value of next-door neighbor is swap(list, k, k+1) done false end for k loop loop end bubblesort //three step swap process void swap (pass-by-reference int[] list, int i, int j) int temp list[i] list[i] list [j] list [j] temp end swap //less than current value(neighbors are out of sorts ) //swap the two values //set done to false Page 13

Insertion Sort - Uses a nested loop process (loop within a loop) to insert each unsorted item in a list into its proper position. void insertionsort(pass-by-reference int[] list) for (int k 1; k < list.length; k++)//outside loop starts at ONE and stops //at end of list int temp list[k] //save copy of current value to be inserted int best k //assume best place is at current position BUT while (best > 0 AND temp < list[best - 1]) // keep looking for a better place list[best] list[best - 1] //shift values over one spot while the previous best best-1 //place is better and haven t reached the start //of the list list[best] temp //insert the current value in the best place end for end insertionsort o Compare this version to example on page 28 of TExES 141 Preparation Manual, CS 8-12 Page 14

The Merge Sort - Uses a divide and conquer recursive approach, repeatedly dividing the list in half until it is looking at only two individual items, merges the two elements back into one sorted list, working back up through each division, merging each pair of sorted sections together into the larger section, until the entire list is has been merged back into sorted array. void mergesort(pass-by-reference int[] list) //method for initial sort call int n list.length int[] temp new int[n] //creates a temporary array the same size as list mergesorthelper(list, 0, n - 1, temp) end mergesort //method that does the divide and conquer recursive process, receiving two arrays and two integers //indicating front and back of portion of the current portion of the list being sorted void mergesorthelper(pass-by-reference int[] list, int front, int back, pass-by-reference int[] temp) if (front < back) //if front and back positions have not crossed and are not the same int mid (front + back)/2 //find the middle position between front and back mergesorthelper(list, front, mid, temp)//sort the left side, from front to mid mergesorthelper(list, mid + 1, back, temp)//sort the right side, mid+1 to back merge(list, front, mid, back, temp) //merge the left and right lists end if end mergesorthelper //method that merges two previously sorted lists, receiving two arrays and three integers //indicating the front, mid, and back of the current portion of the list being sorted. void merge(pass-by-reference int_array list, int front, int mid, int back, pass-by-reference int_array temp) int i front //i marks the front of the left side of the list being sorted int j mid + 1 //j marks the front of the right side of the list being sorted int k front //k marks the front of the temporary list, into which the values //will be merged while (i <= mid && j <= back) //while neither front marker, i or j, have reached //the end of their half of the list if (list[i] < list[j]) //if i s value is less than j s value temp[k] list[i] //put i s value into the temporary list, and i i+1 end if else temp[k] list[j]; j j+1 end else //step i one position to the right //otherwise, put j s value into the temporary list, and //step j one position to the right k k+1 //step k one position to the right //at this point, one of the two halves of the list has been completely loaded into the //temporary array, and the remaining half needs to be cleaned out //if i has not reached the middle, then the left half needs to be cleaned out and loaded //into the temporary list while (i <= mid) temp[k] list[i] //put i s value into the temporary list k k+1 //step both k and i I i+1 //one place to the right //if j has not reached the back, then the right half needs to be cleaned out and loaded //into the temporary list while (j <= back) temp[k] list[j] //put j s value into the temporary list j j+1 //step both k and j k k+1 //one place to the right //load all temporary values in this current list back into the original list for(int x front; x <= back; x x+1) list[x] temp[x] end merge Page 15

The Quick Sort also uses a divide and conquer recursive approach, using a pivot value to create partitions, and then moves all values to the appropriate side of the pivot, repeating the process with each partition until the dividing process reaches a single element, at which time the recursive process ends and returns to the previous level, until the list is sorted. void quicksort (pass-by-reference int[] list, int lo, int hi) if (lo >= hi) //if the current values of lo and hi have met or crossed, return //do not continue this process end if int left lo //left marker gets low end of current portion of list being sorted int right hi //right marker gets high end of current portion of list being sorted int pivot list[(lo+hi)/2] //pivot gets middle position value of current list while ( left < right) //while left and right markers have not met or crossed while (list[left] < pivot) //look for a value to the left of the pivot that is on the //wrong side, and stop there, with left marking that position left left+1 while (list[right] > pivot) //look for a value to the right of the pivot that is on the //wrong side, and stop there, with right marking that position right right-1 if (left <= right) //if the left and right positions have not crossed, swap the two //values at those positions, and swap (list, left, right) left left+1 // step left marker one position to the right, and right right-1// step right marker one position to the left end if quicksort (list, lo, right) //quicksort the left side of the list quicksort (list, left, hi) //quicksort the right side of the list end quicksort void swap (pass-by-reference int[] list, int i, int j) int temp list[i] list[i] list [j] list [j] temp end swap Page 16