COMP 110 chapter 7

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

pass- by- value

passes arguements to a method.

Java.util.Arrays

Contains varo=ious static methods for sorting and searching arrays, filling array elements and returning a string representation of the array. These meethods are overloaded for all primitive types.

null

If a variable does not contian a reference to the array, the value of the variable is null.

Assume int[] scores= {1,20,30,40,50}, what value does java.util.arrays.binarySearch(scores,3) return?

-2

linear search.java

1. public class LinearSearch{ 2. public static int Linear Search (int [] list, int key){ 3. for (int i=0; i< list.length; i++){ if (key== list[i]) 5. return i; 6. } 7.return -1 8.} To better understand this method, trace it with the following statements: 1. int[] list={1 , 4 , 4 , 2 , 5 , -3 , 6 , 2} 2. int i= linearSearch (list, 4);// Returns 1 3. int j= LinearSearch (list, -4);// Returns -1. 4. int k= linearSearch(list, -3);// returns 5

Assume int[] scores={1,20,30,40,50}, what value does java.util.Arrays.binarySearch(scores,30) return?

2

variable- length arguement lists

A variable number of arguements of the same type can be passed to a method: The aprameter in the method is declared as follows: typeName ... parameterName

Array index out of bounds exception

Accessing an array out of bounds is a common programming error. To avoid it, make sure you do not use an index beyond arrayRefvar.length-1 or simply use a foreach loop if possible.

figure 7.9

Let low and high denote , respectively, the first index and the last index of the array that is currently being searched. Initially, low is set to 0 and high is list.leength-1. Let mid denote the index of the middle em=lement, so mid is (Low+High)/2. Figure 7.9 ( pg. 269) shows how to find the key in the list {2,4,7,10,11,45,50,59,60,66,69,70,79} using binary search.

copying reference

Often in a program, you need to duplicate an array or part of an array. In such cases, you could attempt to use the assignment statement (-) as follows: list2=list1; However, the statement only copies the reference value from list1 to list2.

off-by-one error

Programmers often mistakenly reference the first element in an array with index 1. Another common off- by- one error in a loop is using <= where there should be a <.

figure 7.11

Select 1( the smallest) and sw ap it with 2 (the first) in the list. * See figure 7.11 on pg. 271

Sorting Arrays (selection sort)

Selection sort finds the smallest number in the list and then swaps it with the first element. It then finds the smallest number remaining and swaps it with the second element and so on until a single element remains.

Simplify coding

String[] months={"January", "February", ..., "December"); int monthNumber= input.nextInt(); System.out.print("The month is"+month[monthNumber-1]; If you didn't use the months array, you would have to determine the month name using an if- else statement as follows: if(monthNumber==1) System.out.println("the month is January"); else if (monthNumber==2); System.out.peintln("The month is February"); ... else System.out.print("The month is December");

returning an array from a method

When a method returns an array the reference of the array is returned. 1. public static int[] reverse(int[] list){ 2. int[] result= new int [list.length]; 3. for (int i=0, j=result.length-1; 4. i<list.length; i++,j--){ 5.result [j]=list[i]; 6.} 7. return result; 8.} Line 2 creates a nee array result. Lines 3-6 copy elements from array list to array result. Line 9 returns the array. For example, the following statement returns a new array list2 with elements 6,5,4,3,2,1. int[] list1={1,2,3,4,5,6}; int[] list2= reverse(list1)

passing arrays to methods

When passing an array to a method, the reference to the array is passed to the method. the following method displays the elenments in a array: public static void printArray (int [] array){ for(int i=0; i<array.length; i++){ System.out.println(array[i]+""); } } You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2,6, 4, and 2. printArray(new int[]{3,1,2,6,4,2} );

equlas method

You can us ethe equals method if two arrays are strictly equal.two arrays arestrictly equal if their corresponding elements are the same. In the following code, list1 and list2 are equal, but list2 and list3 are not. int [] list1={2,4,7,10}; int[]list2={2,4,7,10}; int [] list3= [4,2,7,10}; System.out.println(java.util.Arrays(list1,list2))//true System.out,prinltn(java.util.Arrays(list2,list3))//false

creating arrays

arrayRefVar= new elementType [array size]; elementtype[] arrrayRefVar= new elementType [array size]

listing 7.8

1. public class selection sort{ 2. public static void Selection Sort(double [] list){ 3. for(int i=0; i<list.length; i++){ 4. double currentMInIndex=i; for(int j=i+1; j<list.length; j++){ 5. if (currentMIn>list[j]){ 6. currentMin= list[j]; 7. currentMinIndex=mj; 8.} 9.} 10. if(currentMinIndex=i){ 11. list[currentMinIndex]= list[i]; 12. list[i]= currentMIn; 13.} 14.} 15.} 16.}

figure 7.10

1. public static int binarySearch( 2. int [] list,int key{ 3. int .ow=0; 4. int high= list.-1; 5. int mid= (low+high)/2; 6. if(key<list[mid]) 7.high= mid-1; 8. else if (key ==list[mid]) 9. return mid; 10. else 11. low= mid+1 12. } version A 1. public sttic int binarySearch( 2. int[] list, int key){ 3. int low=0; 4. int high= list.lengh-1; 5. while(high >=low){ 6. int mid= (low+high)/2; 7. if(key< list[mid]); 8. high= mid-1; 9. else if(key == list[mid]) 10. return mid; 11. low= mid=1; 12. } 13. return -1;// Not found 14.} When the key is not found, low is the insertion point where a key would be insserted to maintain the opder of the list. It is more useful to return the insertion point than -1. The method must return a negative value to indicate that the kay is not in the list.

garbage collection

After the reference value of list1 is copied, and list1 and list2 reference the same array, the array previously referenced by list2 is no longer referenced; it becomes garbage, which will be automatically collected by the Java Virtual Machine in a process called garbage collection.

0 based index

Array indices are 0 based; that is they rabge from 0 to arrayRefVaar.length-1.

array initializers

Combine the declaration, creation aelementnd initialization of an array in one statement using the following syntax: elementType [] arrayRefVar= { value0, value1, ... vlaue 10} For example, the following statement double [] myList ={ 1.9, 2.9. 3.4. 3.5}; declares, creates and initializes the array myList with four statements: double [] myList= new double[4]; myList[0]= 1.9; myList[1]= 2.9; myLIst[2]= 3.4; myList[3]= 3.5;

Binary Search approach

Compares the key element in the middle of the array: 1. If the key is less than the middle element, you need to continue to search for the key only in the first half of the array. 2. If the ktey is equal to the middle element, the search ends with a match. 3. If the key is greaterthan the middle el,ement, you need to continue to search for the key only in the second half of the array.

linear search approach

Compares the key element, key sequentially with each element in the array and continues to do so until the key matches the element in the array or the array is exhausted ithout a match being found. If a match is made, the linear search returns the index of the element that matches the key. If no match is foun, the search returns -1.

Random shuffling

In many applications, you need to randomly reorder the elements in an array, called shuffling. Swap myLIst[i] with myLIst[j] as follows: for(int i=0; i<myList.length; i++){ int j=(int)(Math.random()*myList.length); double temp= myList[i]; myList[i]=myList[j]; myList[j]= temp; } *See diagram on pg.252

Variable- length parameter

In method declaration, you specify the type followed by an elipsis. ONly one variable- lenght parameter may be specified in a method and this parameter must be the last parameter. Any regular parameters must preceed it.

Invoking sort (numbers)

Sorts the whole array numbers. PAralellsort id more efficient if your computer has multiple processors. You can use the binary search method to search for a eky in an array. Ex: int [] list= { 2 , 4 , 7 , 10 , 11 , 45 , 50 , 59 , 60 , 66 , 69 , 70 , 79} System.out.println("1. Index is" + JAva.util.Arrays.binarySearch(list1)) System.out.println(2. Index is"+ java.uti.Arrays.binarysearch(list2)); char[] chars={'a','c','g','x','y','z'} System.out.println("2.Index is"+ java.util.Arrays.binarySearch(chars, 'a')); System.out.println(4. Index is"+ java.util.Arrays.binarySearch(chars, '4')); the output of the preceeding code is as follows: Index is 4 Indes is -6 Index is 0 Index is -4

initializing arrays with random values

for(int i=0; i<myList.length; i++){ myList[i]= Math.rendom()*100; }

Command- line arguements

The main method can recieve string arguements from the command line.You can call a regular method by passng it to actual parameters. public class A{ public static void main(String [] args){ String{} striing={"new York"'"Boston"'"Atlana"} Test Main.main(Strings); } } public class TestMAin{ public staatic void main(String [] args){ for( int i=0; i<args.length; i++); System.out.println(args[i]0; } }

Analyze the following code: public class test{ public static void main(String [] args){ double []x= {2.5,3,4} for(double, value:x) System.out.print(value+""); }

The program dispalys 2.5 3.0 4.0

Analyze the following code; public class Test{ public static void main(String []args){ int [] x=i{1,2,3,4} int []y=x; x= new int[2]; for(int i=0; i,x.length;i++); System.out.println(x[i]+""); }

The program displays 00

array length

The size of an array cannot be changed after the array is created. Size can be obtained using arrayRefVar. length. For example, myIst.length is 10. When an array is created, its elements ae assigned the default value of 0 for numeric primitive data types, 14000 for char types and false for boolena types.

double myList= new double[10]

This statement declares an array variable, myList, creates and array of 10 elements of double type, and assigns its reference to myLIst. To assign the values to the elements, use the syntax arrayRefVar [index]= value; myLIst[0]= 5.6; myLIst[1]= 4.5; myList[3]= 3.3; myList[4]= 13.2; myList[5]= 34.33; myList[6]= 34.0; myLIst[7]= 45.45; myList[8]= 99.993; myList[9]= 1123; double myList= new double[10] * See diagram on pg. 249

find the smallest index of the largest element

Use indexOfMax to denote the index of the largest element.Compare each element in myLIst with max and update indexOfMax if the element is greater than max. double max= myliSt0; int indexOfMax=0; for(int i=0; i<mylist.length; i++){ if(myList[i]>max){ max= myList[i]; indexOfMax=i

toString method

You can also use the toString method to return a string that represents all elements in the array.For example, the following code: int [] list={2,4,7,10} System.out.println(java.util.Arrays.toString(list); displays[2,4,7,10].

passing strings to the main method

You can pass strings to the main methodfrom teh command line when you run the program. The following command line , for example, starts the program, TestMain with three strings: arg 0, arg 1, and arg 2. JAva testMain arg0 arg1 arg2 * A string that contains a space must be enclosed in double quotes. Java TestMain "First num" alpha 53 It starts the program with these strings: First num, alpha and 53. Since first num is a string, it is enclosed in double quotes. You can use 53 instead of "53" in the command line. When the main method is invoked in JAva, the java interpreter creates an array to hold the command- line arguements and pass the array to the reference args. For example, if you invoke a program with n arguements, the java interpreter creates an array such as the one that follows: args=mnewString[n]; The java interpreter than passes args to invoke the main method.

fill method

You can usee the fill mehtod to fill in al or part of the array. int [] list1={2,4,7,10}; int [] list2={2,4,7,7,10}; java.util.Arrays(list1,5)//Fill 5 to the whole array; java.util.Array(list2,5,8);// Fill 8 to a partial array

Which of the following statements are valid? a. double d [] = new double[30] b. char[] c= new char[4]{'a','b','c','d'} c. char[] c= new char(): d. int [] i= {3,4,3,2}

a. double d[]= new double[30] d. int []i= {3,4,3,2}

array copy method

can be used to copy arrays instead of using a oop. the syntax is arraycopy(SourceArray,0,targetArray,0,AourceArray.length);

code for selection sort using (double [] list)

double []list={1,9,4,5,6,6,5,7,-4,9} Selection.dort.SelectionSort(list1);

shifiting elements

double tfemp= myList[0]; for(int i=0; i<myList.length; i++){ myLIst[i-1]= myLsit[i]; } myList[myList.length-1]=temp; *See diagram on pg. 252

Summing all elements

double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; }

declaring array variables (element type)

elementType[] arrayOfRefVar; or elementType arrayOfrefVar[];// Allowed, but not preferred The element type can be any data type and all elements will comtain the same data type. Ex: double[] myList; or double myLIst[]; // Allowed, but not preferred

for each loop

enables you to traverse the array sequentially without using an index variable. Ex: for(double e: myList){ System.out.println(e); } In general, the syntax of a for each loop is: for(elementType:element:arrayRefVar){ }

print character array

for an array of the char[] type, it can be printed using one print statement

pass by sharing

for arguements of array type only; the array in the method is the same as the array being passed.

displaying arrays

for(int i= 0; i<myList.length; i++){ System.out.print(myList[i]+ ""); }

Code for selection sort

for(int i=0; i< list.length-1; i++){ Select the smallest element in the list [i... list.length-1]; swap the smallest element with list[i] if necesary. // list[i] is in the correct postition; // The next iteration applies on list [ i+1 ... lis.length-1] }

initializing arrays with input values

java.util.Scannernew java.util.Scanner input= (system.in); System.out.print("Enter"+ mylsit.length+ "values"); for(int i=0; i< myLIst.length(); i++); myList[i]= input.nextDouble();

For the binary search method in section 7.10.2, what is high and low after the first iteration of the while loop hen invoking binarySearch (new int[]{1,2,4,6,8,10,15,20},11)?

low is 5 and high is 5

processing arrays(using for loops)

use a for loop for one of two reasons: 1. All of the lemenets in an array are of the same type. they are evenly processed in hte same fashion using a loop. 2. Since the size of the array is known, it is natural to use a for loop.

finding the largest element

use max to store the largest element. to find the largest element, compare each element with max and update max if the element is greater than max. double max= myLIst[0]; for(int i=0; i< myList.length; i++){ if(myList[i]>max) max= myList[i]; }

sort ornparallel sort method

used to sort a whole or partial array. double[] numbers={6.0 , 4.4 , 1.9 , 2.9 , 3.4 , 3.5} JAva.util.Arrays.sort(numbers) Java.util.Arrays.ParalellSort(numbers); char[] chars={'a', 'A', '4', 'F', D', 'P'} java.util.Arrays.sort(chars 1,3); java.util.Arrays.paralellSort(chars 1,3);


Kaugnay na mga set ng pag-aaral

EXAM 3 Chapter 32 Skin and wounds

View Set

Chapter 5 - Missed Questions - 72%

View Set