CSE 007: Midterm #2 (10/30)

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Algo #2: Binary Search - Example 1

Ex for an array in ascending order: First, compare the key with the element in the middle of the array: 1. If the key is less than the middle element, continue searching for key in the first half of the array 2. If the key is equal to the middle element, the search ends 3. If the key is greater than the middle element, continue to search for the key in the second half of the array **int list= {22,44,55,33,11,99,77,66,88}; key = 33;

T/F: The array size is fixed when the array is declared

False

T/F: The elements in an array must be of a primitive type

False

Initializing arrays

Format: type name[size] = { list of elements }; ● Can initialize arrays in the same line as declaration ● The list of elements goes in { } and is separated by commas ● may leave size box empty when initializing on the declaration line - compiler sets size. ● size must leave room for null-character '\0' ● Can also initialize with for loops (good with regular patterns) ● Special case strings: null-terminated character arrays ● can initialize on the declaration with a string literal ● Ex: char name[7] = "Marvin"; ● Ex: int list[5] = {1, 3, 5, 9, 10};

Iterating through Arrays using Loops

General Algorithm: ● Use for loop ● Run from first element (index = 0) to last element (index = length-1)

Example 2: Iterating through Arrays using Loops

Scanner keyboard = new Scanner(System.in); int size = keyboard.nextInt(); double[] numbers = new double[size]; for (int i=0; i<numbers.length; i++){ numbers[i] = keyboard.nextDouble( ); } keyboard.close( );

Algo #1: Linear Search - Example

Scanner scan = new Scanner (System.in); int list= {22,44,55,33,11,99,77,66,88}; int key = 55; int index=-1; for(int i=0; i<list.length; i++{ if (list[i] == key { index = i; break; } } if(index != -1){ System.out.println(key + " was found at index="+ index); } else { System.out.println(key+ " was not found "); }

Insertion Sort: How it works?

Sorts a list of values by repeatedly inserting a new element into a sorted sublist until the entire list is sorted

array

a collection of several variables of the same type a) grouped together in memory, rather than handling many variables b) allows a single pt of reference

Arrays: The Basics

a) elementType[] arrayName = new elementType[numElements]; > Declares and allocates memory for numElements variables of type elementType with default values b) arrayName[index] = elementType value; System.out.println(arrayName[index]); > Assign values and subsequently access individual elements in arrayName c) elementType[] arrayName = {value1, value2, value3, ... } > Syntax to combine arrayName declaration, creation and initialization* *Best for small arrays

selection sort algorithm

an algorithm for sorting a collection of values that repeatedly finds the largest values in the unsorted section of the list and moves them into the correct position: 1. Iterate through the entire list 2.. Set the current element as minimum value 3. Iterate through the rest of the list to compare a. If you find a value smaller than minimum value, change minimum value 4. If the minimum does change, the current element and new minimum will swap before the next iteration

Creating Array Variables

format: arrayName= new datatype[number of elements]; ● Ex: numList = new double[10]; cardSuit = new String[4];

Declaring Array Variables

format: datatype [size] arrayName; ● the type can be any basic type or any user-defined type ● the size must be known by the compiler, so it must be a positive integer literal or constant. ● arrays are declared like normal variables with the addition of [ ] between type and name ● the declaration does not specify the number of elements ● declaring an array does not reserve (allocate) memory for the array elements ● Ex: double [ ] numList; String [ ] cardSuit;

Algo #2: Binary Search - Example 2 > for an array in ascending order

import java.util.Arrays; . .. Arrays.sort(numList); //numList = {2,3,5,7,8,9,13}; ... int mid, low, high; keyIndex = -1; low = 0; high = numList.length-1; while(high>=low){ mid = (high+low)/2; if (numList[mid]< key){ low = mid+1; } else if(numList[mid]>key){ high = mid-1; } else { keyIndex = mid; break; } } if(keyIndex!=-1){ System.out.println(key + " was found at index="+ keyIndex); } else { System.out.println(key+ " was not found in numList"); }

ArrayReversal.java (demo found in Wk 9 Resources) > Input: 10 20 30 40 50 60 70 80 - Array Example

import java.util.Scanner; import java.util.Arrays; public class ArrayReversal { public static void reverseVals(int[] arrVals) { int i;// Loop index int tempValue; for (i = 0; i < (arrVals.length / 2); ++i) { tempValue = arrVals[i]; // Do swap arrVals[i] = arrVals[arrVals.length - 1 - i]; arrVals[arrVals.length - 1 - i] = tempValue; } } public static void main(String[] args) { Scanner scnr = new Scanner(System.in); final int NUM_VALUES = 8; // Array size int[] userVals = new int[NUM_VALUES]; // User values int i; // Loop index // Prompt user to populate array System.out.println("Enter " + userVals.length + " values..."); for (i = 0; i < userVals.length; ++i) { System.out.print("Value: "); userVals[i] = scnr.nextInt(); } // Call method to reverse array values reverseVals(userVals); // Print updated arrays System.out.print(Arrays.toString(userVals)); }

insertion sort algorithm - Example

int currentElement; for(int i=1; i < numbers.length; i++){ >>>>>currentElement=numbers[i]; for(int j = i-1; j >= 0&& numbers[j]> currentElement; j--){ numbers[j+1] = numbers[j]; } numbers[j+1] = currentElement; }

selection sort algorithm - Example

int[] numbers = { 9 , 1 , 6 , 5 , 2 , 3 }; for(int i=0; i < numbers.length -1; i++){ int indexMin = I; int min = numbers[i]; for(int j=i+1; j < numbers.length; j++){ if(min > numbers[j]){ min = numbers[j]; indexMin = j; } } if(indexMin != i){ numbers[indexMin] = numbers[i]; numbers[i] = min; } }

Example: int Array

int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]

Passing by Value versus by Reference

● Arguments are passed by value with the exception of arrays ● Passing by value passes a copy of the current value of an argument to a method ● Passing by reference passes a pointer (reference variable) to the memory location of an argument to a method ● int[] thisArray = {1,2,3,4,5}; someMethod(thisArray);

multidimensional array

● Arrays of Arrays with each element of the array holding the reference to another array ● Created by appending one set of square brackets ([]) per dimension

Algo #2: Binary Search

● Binary Search is an efficient way to sort an array, but requires the array to be sorted. ○ Either in ascending or descending order ○ For now, we can use a method from the Arrays class to do this: import java.util.Arrays; Arrays.sort(arrayName);

ArrayIndexOutOfBounds Exception

● Common error with arrays ● Index less than 0 or greater than or equal to length ● Might have seen this error with Strings

Algo #1: Linear/sequential Search

● Compares the key sequentially with each element in the array ● If a match is found: ○ return the index of the element that matched ● Otherwise, if it reached the end of the array without finding a match ○ return -1 (or some other dummy/useful value) ● int list= {22,44,55,33,11,99,77,66,88}; key = 55;

Two-Dimensional (2D) Array Basics

● Data in a table or a matrix can be represented using a 2D array ● An element is accessed through a row and column index ● General Syntax: elemType[][]arrayName = new elemType[row][col] ● Example: int [][]twoDArr = {{1,2,3,4}, {5,6,7,8}, {9, 10, 11, 12}};

Method Overloading

● Define methods with the same name but different signature ● Useful for methods performing the same function with differing input ○ Different parameter lists ● Can't be overloaded based on return type ● Make programs clearer/more readable

referencing an array

.use an index(0 ->(Number of Elements -1)) ● Ex: int[ ] myList = new int[5];

Defining a Method - Example

//header public static int findMax(int x, int y){ //body int max; if (x>y){ max=x; } else{ max x =y; } return max; }

Selection Sort: How it works

1. Finds the smallest number in the list and swaps it with the first element. 2. Then, it finds the next smallest element and swaps it with the second element. 3. This pattern continues until only a single value remains

The Insertion Sort Algorithm

1. Iterate through the list one element at a time, sorting as you go so that for any value of i, numbers[0...i] is sorted 2. Iterate through the sorted sublist (everything before the element that you are currently on) to insert the current element

Invoking a Method

**Key components: > Method Call ● arguments passed by value to parameters ● values of variables passed

Defining a Method

**Key components: > Method Header ● Modifier(s) ● Return value type --> void body ● Method name ● Formal parameters/parameter list ● Method Signature > Method Body: ● Return value (if not defined as void)

compareTo method - Example

String [] sevenDwarfs = {"Sleepy", "Happy","Bashful", "Sneezy","Grumpy","Dopey", "Doc"}; System.out.println(sevenDwarfs[3].compareTo(sevenDwarfs[0])); System.out.println(sevenDwarfs[5].compareTo(sevenDwarfs[1])); System.out.println(sevenDwarfs[4].compareTo(sevenDwarfs[2])); System.out.println(sevenDwarfs[3].compareTo(sevenDwarfs[3])); System.out.println(sevenDwarfs[6].compareTo(sevenDwarfs[4])); System.out.println(sevenDwarfs[5].compareTo(sevenDwarfs[6])); System.out.println(sevenDwarfs[3].compareTo(sevenDwarfs[5]));

Example: String Array

String[] colors = {"Red", "Orange","Yellow", "Green","Blue","Purple"}; System.out.println(colors[1]); System.out.println(colors[4]); System.out.println(colors[1].equals(colors[2])); System.out.println(colors.length); System.out.println(colors[4].length()); colors[0] = "Lehigh"; for(int i = colors.length-1; i >=0; i--){ System.out.println(colors[i]); }

Example 1: Iterating through Arrays using Loops

String[] list = new String[10]; for(int index=0; index<list.length; index++){ System.out.println(list[indes]); }

Selection Sort with Strings - Example

String[] womenInTech = {"Sandberg, Sheryl", "Schneider, Erna", "Bartik, Jean", "Klawe, Maria", "Hopper, Grace", "Borg, Anita", "Lovelace, Ada"}; int indexMin; String min; for(int i=0; i < womenInTech.length -1; i++){ indexMin = i; min = womenInTech[i]; for(int j=i+1; j < womenInTech.length; j++){ __________if(womenInTech[indexMin].compareTo(womenInTech[j]) > 0 ){ indexMin = j; min = womenInTech[j]; } } if(indexMin != i){ womenInTech[indexMin] = womenInTech[i]; >>>>>womenInTech[i] = min; } }

Comparing & Searching Strings - Example

String[] womenInTech = {"Sandberg, Sheryl", "Schneider, Erna", "Bartik, Jean", "Klawe, Maria", "Hopper, Grace", "Borg, Anita", "Lovelace, Ada"}; String key = "Lovelace, Ada"; System.out.println(key.compareTo(womenInTech[0])); System.out.println(key.compareTo(womenInTech[1])); System.out.println(key.compareTo(womenInTech[2])); System.out.println(key.compareTo(womenInTech[3])); System.out.println(key.compareTo(womenInTech[4])); System.out.println(key.compareTo(womenInTech[5])); System.out.println(key.compareTo(womenInTech[6]));

call stack

The call stack is all of the call frames of the currently executing function calls (e.g. the main function call and all of its helper functions). These call frames are arranged in a stack, with the original function up top, and the most recent function call at the bottom. If the current function calls a helper function, you add a new frame to the bottom. When a helper function completes, you remove the call frame from the stack.

T/F: Every element in an array has the same type

True

T/F: The array size is fixed when the array is created

True

Clarifying compareTo( )

myStr1.compareTo(myStr2) ● Compares the character sequence of each String ○ Not the total of the unicode values of each character ● Lexicographic comparison: ○ If myStr1.equals(myStr2) ■ .compareTo() returns 0 ○ If myStr1 precedes myStr2 ■ .compareTo() returns negative value ( < 0) ○ If myStr1 follows myStr2 ■ .compareTo() returns positive value ( > 0)

OverloadArrays.java (equals() - Array Example

public class OverloadArrays { public static void main(String[]args){ int[] arr1 = {1,2,3,4,5}; int[] arr2 = {1,2,3,4}; int[] arr3 = {1,2,3,4,5}; int[] arr4 = {1,2,3,4,4}; System.out.println(equals(arr1, arr2)); System.out.println(equals(arr1, arr3)); System.out.println(equals(arr1, arr4)); } public static boolean equals(int[]list1, int[]list2){ if(list1.length != list2.length ){ return false; }else { for(int i = 0; i < list1.length; i++){ if(list1[i] != list2[i]){ return false; }}} return true;} public static boolean equals(char[] list1, char[] list2){ if(list1.length != list2.length ){ return false; }else { for(int i = 0; i < list1.length; i++){ if(list1[i] != list2[i]){ return false; } } } return true; }

Passing by Value versus by Reference - Example

public class PassBy{ public static void main(String[]args){ int[] numbers = {100, 200, 300, 400}; printArray(numbers); int[] newNumbers = copyArray(numbers); doubleArrayContent(numbers); printArray(numbers); //int[] newNumbers = copyArray(numbers); printArray(newNumbers); } public static void printArray(int[] list){ for(int i=0; i < list.length; i++){ System.out.print(list[i]+ " "); } System.out.println(); } public static void doubleArrayContent(int[] list){ for (int i=0; i<list.length; i++) list[i] = list[i] * 2; } public static int[] copyArray(int[] list){ int[] newList = new int[list.length]; for(int i=0; i<list.length; i++){ newList[i] = list[i]; } return newList; } }

twoDString.java - 2D Array Example

public class twoDString { public static void main(String[]args){ String[][] classInfo = {{"Kallie Ziltz", "Bethlehem, PA", "alumna"}, { }, { }, { }, { }}; for(int row = 0; row < classInfo.length; row++){ >>>>>>>>>>for(int col = 0; col < classInfo[row].length; col++){ System.out.print(classInfo[row][col]+ "\t"); } System.out.println(); } } }

Example: Overloading print (equals( ))

public static void printArray(int[] list){ for(int i=0; i < list.length; i++){ System.out.print(list[i]+ " "); System.out.println(); } }

Defining CardTrick methods & Calling CardTrick Methods from main (Methods - Example)

● Defining CardTrick methods: public static String getSuitName(int cardNum){ int suit = (cardNum-1)/ 13; String suitName = ""; switch(suit){ case 0: suitName = "Diamonds"; break; case 1: suitName = "Clubs"; break; case 2: suitName = "Hearts"; break; case 3: suitName = "Spades"; break; } return suitName; } ● Calling CardTrick Methods from main: public static String getCardIdentity(int cardNum){ int card = cardNum% 13; String cardIdentity = ""; switch(card) { case 0: cardIdentity = "King"; break; case 1: cardIdentity = "Ace"; break; case 11: cardIdentity = "Jack"; break; case 12: cardIdentity = "Queen"; break; default: cardIdentity= Integer.toString(card); } return cardIdentity; }

Accessing elements in an array

● Ex: int[ ] myList = {22,31,4,46,19} myList[0] = 22 myList[1]= 31 myList[2] = 4 myList[3] = 46 myList[4] =19 ● For any array of n elements: - the 1st element is at indez =0 - 3rd element is at index = 2; - the kth element is at index = k-1; ● number of elements (n) is always known ● elements are same type ● each element treated like an individual variable

Methods

● Flexible type of code container ○ Collection of statements that work together to perform a function/operation ○ Allows us to run code repeatedly without writing redundant code ● Create other methods outside of the main method, but within the same class. ○ Methods can be used within the same class and in other classes/programs (but more on that in a few weeks!) ● Have a predefined input and predefined output ● We refer to running or evaluating a method as calling a method

Comparing & Searching Strings

● Method compareTo() from String class compares strings lexicographically ○ Compares unicode value of characters in sequence ● Syntax: String myStr1 = "Hello"; String myStr2 = "Hello"; System.out.println(myStr1.compareTo(myStr2)); ● Return values: ○ If myStr1.equals(myStr2) ■ .compareTo() returns 0 ○ If myStr1 precedes myStr2 ■ .compareTo() returns negative value ( < 0) ○ If myStr1 follows myStr2 ■ .compareTo() returns positive value ( > 0)

Searching Algorithms

● Process of looking for a specific element in an array ● Often, refer to element as key ● Example: We want to search a 10 element array of integers for a number that the user will input

manipulating arrays

● Searching an array for a specific value to get the index at which it is placed (the binary Search method) ● Comparing two arrays to determine if they are equal or not (the equals method) ● Filling an array to place a specific value at each index (the fill method) ● Sorting an array into ascending order

# of comparisons LINEAR search

● best case: one comparison, and matches X right away ● average case: (n+1)/2 ● worst case: n comparisons, and either matches the last item in the list or doesn't match anything

for-each loops

● enhanced for loop ● traverse the complete array sequentially w/out an index variable ● Not a good option if you want to traverse in a different order, or change elements in the array ● General sntax: for(elementType value: arrayName){ //Process value }

Examples of Methods

● public static void main(String[ ]args){} ● Math.random ● System.out.println("Hello"); ● MyScanner.nextInt( ); ● input.hasNextDouble( ); ● Arrays.sort( ) ● String1.equals(String2); ● Str1.compareTo(Str2);


Kaugnay na mga set ng pag-aaral

The Client with Urinary Tract infection

View Set

Prep U: Ch 25: Disorders of Renal Function

View Set

Chapter 9 Questions: Glucose Metabolism

View Set

Nervous system: action potentials, graded potentials, and synaptic transmission

View Set

FIN3715 Chapter 7, Finance Chp. 6, EXAM 2 CHAPTER 7 and 8 FIN

View Set

Chapter 19: Conditions Existing Before Conception

View Set

6.2.5 - Enumeration Countermeasures (Practice Questions)

View Set

ATI Fluid, electrolyte, and Acid-Base Regulation Test

View Set