selection sort and merge sort file input/output. hw 2 – section 02 avg = 96/100

Post on 04-Jan-2016

222 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Selection sort and Merge sortSelection sort and Merge sort

File input/outputFile input/output

Selection sort and Merge sortSelection sort and Merge sort

File input/outputFile input/output

HW 2 – Section 02• Avg = 96/100

0

20

40

60

80

100

120

0 10 20 30 40

Series1

HW 2 – Section 01• Avg = 89/100

0

20

40

60

80

100

120

0 10 20 30 40

Series1

HW2 Answers1. The difference between the two String

methods: equals and equalsIgnoreCase isA. equals compares two string objects, and

ignores case considerationsb. equalsIgnoreCase compares two string objects,

and ignores case considerationsc. both equals and equalsIgnoreCase compare

two string objects and ignore case considerations.

D. both equals and equalsIgnoreCase compare two string objects and consider cases

HW2 Answers2. In order to determine how many

characters contained in a String object myString, we use:

a. myString.size()b. myString.sizec. myString.lengthd. myString.length()

HW2 Answers3. Which of the followings is the

constructor of the class Faculty?a public int Faculty (long SSN ) {…..}b public Faculty(long SSN) { ….}c public void Faculty(long SSN) {….}

d. public Boolean Faculty(long SSN) {….}

HW2 Answers4. Fixed-size array declaration has two

limitations: inability to handle an overflow situation and possible under utilization of allocated spacea. Trueb. False

HW2 Answers5. Consider the following method:

public int compute(int amt) {int temp = amt * 4;return temp;

}How would you characterize amt?a. A data member/ an attributeb. A parameterc. A return valued. A return data type

HW2 Answers6. A code fragment that declare an

array of type double named gpa is:a. double gpa;b. double gpa{ };c. double gpa[ ];d. double gpa( );

HW2 Answers7. Which of the following is incorrect:

a. double testArray[] = new double[12];b. double[] testArray = new double[12];c. double[] testArray;d. double[] testArray[12];

HW2 Answers8. Suppose an array contains 256

elements. What are the least and the greatest number of comparisons for a successful search using linear search?a. 1 and 256b. 0 and 256c. 1 and 8d. 0 and 8

HW2 Answers9. Suppose an array (SORTED) contains

256 elements. What are the least and the greatest number of comparisons for a successful search using binary search?a. 1 and 256b. 0 and 256c. 1 and 8d. 0 and 8

HW2 Answers10. Given a one dimensional array

myArray, what is the correct way of getting the number of elements in this array. a. myArray.length b. myArray.length - 1 c. myArray.size d. myArray.size – 1

HW2 AnswersMatching11.

public void setExchangeRate (double rate) {exchangeRate = rate;

}

C B E

A

D

HW2 AnswersMatching12.

B D F

A G

C E

HW2 AnswersMatching12.

B D F

A

C

E

G

HW2 AnswersMatching– 13. A code fragment that declares an array named

profession and allocate the memory to store 20 values of type String:=;

– new– [20]– profession– String[ ]– String

= ;CD A E B

HW2 Answers

Looks for a value in a linear sequence

Looks for a value by checking the element in The middle of an array

14.

B

A

A. Binary searchB.Linear search

HW2 Answers15.

The following method is invalid. Why?public void myMethod(int myParams) {

return (myParams*2);}

1. Void method should not return an int. It should return nothing.

HW2 Answers16.

public String ClassB( ) {description = “Unknown”;return description;

}

1. String should be removed because Constructors don’t need return data type2. Return description should also be removed because constructorsshould not return anything.

HW2 Answers17.

CurrencyConverter converter = new CurrencyConverter();double amount = converter.feeRate;

1. feeRate is a private attribute and therefore is not assessibleoutside of CurrencyConverter class.

HW2 Answers18.

int number[] = new int[10];for (int i=0; i<number.length; i++) {

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

if (i%2 == 0)System.out.println(" "+ number[i]);

}

0 2 4 6 8

HW2 Answers19obj = new QuestionOne(); // => amount =10Obj.setAmount(0.15); // =>amount = 10*(0.15+1) =

10*1.15 = 11.50

Updated amount is 11.50

HW2 Answers20

resultStr=“Spring Break" lengthStr =12

Selection Sortpublic void selectionSort(int[]

number) {int minIndex, size, temp;size = number.length;

Selection Sortfor (int i=0; i<=size-2; i++) {

minIndex = i;for (int j=i+1; j<=size-1; j++) {

if (number[j] < number[minIndex])minIndex=j;

}temp= number[i];number[i]=number[minIndex];number[minIndex] = temp;

}}

Selection Sort

• i=0:minIndex=0j= 1 number[1]=20 > number[0]=18j=2 number[2]=17 < number[0]=18

minIndex = 2j=3 number[3]=40 > number[2]=17j=4 number[4]=22 > number[2]=17j=5 number[5]=27 > number[2]=17j=6 number[6]=30 > number[2]=17

Number

402018 17 22 27 30

0 1 2 3 4 5 6

Selection Sort

• i=0:minIndex=2temp= number[0] = 18number[0]=number[2] = 17number[2] = temp = 18;

Number

402018 17 22 27 30

0 1 2 3 4 5 6

Selection Sort

• i=0:minIndex=2temp= number[0] = 18number[0]=number[2] = 17number[2] = temp = 18;

Number

402017 18 22 27 30

0 1 2 3 4 5 6

Selection Sort

• i=1:minIndex=1j=2 number[2]=18 < number[1]=20

minIndex = 2j=3 number[3]=40 > number[2] = 18j=4 number[4]=22 > number[2]=18j=5 number[5]=27 > number[2]=18j=6 number[6]=30 > number[2]=18

Number

402017 18 22 27 30

0 1 2 3 4 5 6

Selection Sort

• i=1:minIndex=2temp= number[1] = 20number[1]=number[2] = 18number[2] = temp = 20;

Number

402017 18 22 27 30

0 1 2 3 4 5 6

Selection Sort

• i=1:minIndex=2temp= number[1] = 20number[1]=number[2] = 18number[2] = temp = 20;

Number

401817 20 22 27 30

0 1 2 3 4 5 6

Selection Sort

• i=2:minIndex=2j=3 number[3]=40 > number[2] =20j=4 number[4]=22 > number[2]=20j=5 number[5]=27 > number[2]=20j=6 number[6]=30 > number[2]=20

Number

401817 20 22 27 30

0 1 2 3 4 5 6

Selection Sort

• i=2:minIndex=2j=3 number[3]=40 > number[2] =20j=4 number[4]=22 > number[2]=20j=5 number[5]=27 > number[2]=20j=6 number[6]=30 > number[2]=20

Number

401817 20 22 27 30

0 1 2 3 4 5 6

Selection Sort

• i=3:minIndex=3

j=4 number[4]=22 < number[3]=40 minIndex = 4

j=5 number[5]=27 > number[4]=22j=6 number[6]=30 > number[4]=22

Number

401817 20 22 27 30

0 1 2 3 4 5 6

Selection Sort

• i=3:minIndex=4

temp= number[3] = 40number[3]=number[4] = 22number[4] = temp = 40;

Number

221817 20 40 27 30

0 1 2 3 4 5 6

Selection Sort

• i=4:minIndex=4j=5 number[5]=27 < number[4]=40

minIndex=5j=6 number[6]=30 > number[5]=27

Number

221817 20 40 27 30

0 1 2 3 4 5 6

Selection Sort

• i=4:minIndex=5

temp= number[4] = 40number[4]=number[5] = 27number[5] = temp = 40;

Number

221817 20 40 27 30

0 1 2 3 4 5 6

Selection Sort

• i=5:minIndex=5j=6 number[6]=30 < number[5]=40

minIndex=6

Number

221817 20 27 40 30

0 1 2 3 4 5 6

Selection Sort

• i=5:minIndex=6temp= number[5] = 40number[5]=number[6] = 30number[6] = temp = 40;

Number

221817 20 27 40 30

0 1 2 3 4 5 6

Selection Sort

• i=5:minIndex=6temp= number[5] = 40number[5]=number[6] = 30number[6] = temp = 40;

Number

221817 20 27 30 40

0 1 2 3 4 5 6

Concepts1. String class, methods for String class (length,

substring,compareTo,indexOf…)Week 5 slides

2. Instantiable classes:Private/public attributes/methodsDifferent between attribute and methodsConstructorsParameters passing for methodsWeek 7-8 slides

Concepts3. Array:

Definition, how to declare an array, how to allocate memory, how to initialize valuesHow much memory is needed for an arrayHow to determine how many elements an array hasPassing an array to a method (passing by reference)

Week 9 slides

Concepts4. Search and Sorting

Linear SearchBinary Search

(Week 10-11)

Merge Sort

• Start=0, end = 6, mid=(6+0)/2 = 3

Number

402018 17 22 27 30

0 1 2 3 4 5 6

2018 4017 22 27 30

Merge Sort. Start=0, end = 3, mid=(3+0)/2 =

1

. Start=4, end =6, mid=(4+6)/2=5

2018

22 27 30

4017

Passing Array to Methods

• When an array is passed to a method, only its reference is passed. A copy of the array is not created in the method.

That means:we pass the identifier for that array which in fact is a reference to a start address of the array.

Passing Array to Methods

Assuming changeArrayValue is one method of a class named ArrayClass

public void changeArrayValue(int[] arrayChanged) {for (int i=0; i< arrayChanged.length-1; i++)arrayChanged[i] += 1;

}

We call this method as:

Passing Array to Methods

ArrayClass anObj = new ArrayClass();int number[5] = new int[5];for(int i=0; i<number.length; i++)

number[0] = i;

anObj.changeArrayValue(number);

Passing Array to Methods

for(int i=0; i<number.length; i++)number[i] = i;

anObj.changeArrayValue(number);

0 1 2 3 4

1 2 3 4 5

number

number

Final Exam• Section 01: MWF begins 12:05-

12:55pmMonday, May 08, 2006. 3:15-5:15pm

• Section 02: MWF begins 1:10-2pmWednesday, May 10, 2006: 1-3pm

File Input output• File input: the action of reading

data from a file• File output: the action of

writing/saving data to a file• Why is it important?

. Limited memory

. Some data is needed immediately, others are needed monts/weeks/.. from now

File Input output• File input: the action of reading

data from a file• File output: the action of

writing/saving data to a file• Why is it important?

. Limited memory

. Some data is needed immediately, others are needed monts/weeks/.. from now

File objects• To operate on a file, we must first create a File object (from java.io) and associate this file object to a

specific file.

• How to create a file object:

File <variable_name> = new File(<filename>);

ORFile <variable name>=new File(<directory>, <file name>);

File Class• Go to

http://java.sun.com/j2se/1.3/docs/api/java/io/File.html

• See the constructors of File class

File(String pathname)           Creates a new File instance by converting the given pathname string into an abstract pathname

Examples

File inFile = new File(“sample.dat”);

File inFile = new File(“C:/SamplePrograms/test.dat”);

Opens the file sample.dat in the current directory.

Opens the file sample.dat in the current directory.

Opens the file test.dat in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname.

Opens the file test.dat in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname.

File myFile = new File(“C:\\mydocuments”,”sample.dat”);

(Windows)File myFile = new File(“C:/mydocuments”,”sample.dat”);

(Unix)

Example (continue)

File I/O

Low level I/O High level I/O Text file I/O

Treat a fileAs a set of bytes

TreatA file As a set of data of

primitiveData type

TreatA file As a set of text

(or String)

Low-Level File I/O

• To read data from or write data to a file, we must create one of the Java stream objects and attach it to the file.

• A stream is a sequence of data items, usually 8-bit bytes.

• Java has two types of streams: an input stream and an output stream.

• An input stream has a source form which the data items come, and an output stream has a destination to which the data items are going.

Streams for Low-Level File I/O

• FileOutputStream and FileInputStream are two stream objects that facilitate file access.

• FileOutputStream allows us to output a sequence of bytes; values of data type byte.

• FileInputStream allows us to read in an array of bytes.

Low level data inputStep 1: Create a File object Step 2: Create a FileInputStream

objectStep 3: Declare an array to keep input

data, allocate memory for this arrayStep 4: Read data and process data if

neededStep 5: Close the file

Sample: Low-Level File Input

//set up file and streamFile inFile = new File("sample1.data");FileInputStream inStream = new FileInputStream(inFile);

//set up an array to read data inint fileSize = (int)inFile.length();byte[] byteArray = new byte[fileSize];

//read data in and display theminStream.read(byteArray);for (int i = 0; i < fileSize; i++) {

System.out.println(byteArray[i]);}

//input done, so close the streaminStream.close();

Low level data outputStep 1: Create a File object Step 2: Create a FileOutputStream

objectStep 3:Get data readyStep 4:Write data to output streamStep 5: Close the file

Sample: Low-Level File Output

//set up file and streamFile outFile = new File("sample1.data");

FileOutputStream outStream = new FileOutputStream( outFile );

//data to savebyte[] byteArray = {10, 20, 30, 40,

50, 60, 70, 80};

//write data to the streamoutStream.write( byteArray );

//output done, so close the streamoutStream.close();

Streams for High-Level File I/O

• FileOutputStream and DataOutputStream are used to output primitive data values

• FileInputStream and DataInputStream are used to input primitive data values

• To read the data back correctly, we must know the order of the data stored and their data types

Setting up DataOutputStream• A standard sequence to set up a DataOutputStream object:

Sample Outputimport java.io.*;class Ch12TestDataOutputStream { public static void main (String[] args) throws IOException {

. . . //set up outDataStream

//write values of primitive data types to the streamoutDataStream.writeInt(987654321);outDataStream.writeLong(11111111L);outDataStream.writeFloat(22222222F);outDataStream.writeDouble(3333333D);outDataStream.writeChar('A');outDataStream.writeBoolean(true);

//output done, so close the streamoutDataStream.close();

}}

Setting up DataInputStream

• A standard sequence to set up a DataInputStream object:

Sample Inputimport java.io.*;class Ch12TestDataInputStream { public static void main (String[] args) throws IOException { . . . //set up inDataStream

//read values back from the stream and display them System.out.println(inDataStream.readInt()); System.out.println(inDataStream.readLong()); System.out.println(inDataStream.readFloat()); System.out.println(inDataStream.readDouble()); System.out.println(inDataStream.readChar()); System.out.println(inDataStream.readBoolean());

//input done, so close the stream inDataStream.close(); }}

Reading Data Back in Right Order

• The order of write and read operations must match in order to read the stored primitive data back correctly.

Textfile Input and Output

• Instead of storing primitive data values as binary data in a file, we can convert and store them as a string data.– This allows us to view the file content using any text

editor• To output data as a string to file, we use a

PrintWriter object• To input data from a textfile, we use FileReader and

BufferedReader classes– From Java 5.0 (SDK 1.5), we can also use the Scanner

class for inputting textfiles

Read data from a text fileStep 1: Create a File object Step 2: Create a FileReader objectStep 3: Create a BufferedReader objectStep 4: Read line by line

Step 5: Convert String object to primitive data type as necessary

Step 6: Close the file

Create FileReader and BufferedReader objects

How to create a FileReader ojbect:FileReader <variable_name> = new FileReader(<name of a File ojbect>);

How to create a BufferedReader object:BufferedReader <variable_name> = new

BufferedReader(<name of a FileReader object);

How to read a line<bufferedReader object name>.readLine();

Example – Reading a text file

E:\Temp\data.dat

It's been 84 years, and I can still smell the fresh paint.

The china had never been used. The sheets had never been slept in.

Titanic was called the Ship of Dreams, and it was. It really was.

Example – Reading a text fileimport java.io.*;

public class FileExample{public static void main (String[] args) throws IOException {

File inFile = new File("e:\\Temp\\data.dat");FileReader fileReader = new FileReader(inFile);BufferedReader bufferReader = new

BufferedReader(fileReader);String inputStr;

inputStr = bufferReader.readLine();while (inputStr != null) {

System.out.println(inputStr);inputStr = bufferReader.readLine();

} // end of while

bufferReader.close();System.exit(0);

}}

Package that contains all classes for File I/O

Example – Reading a text fileimport java.io.*;

public class FileExample{public static void main (String[] args) throws IOException {

File inFile = new File("e:\\Temp\\data.dat");FileReader fileReader = new FileReader(inFile);BufferedReader bufferReader = new

BufferedReader(fileReader);String inputStr;

inputStr = bufferReader.readLine();while (inputStr != null) {

System.out.println(inputStr);inputStr = bufferReader.readLine();

} // end of while

bufferReader.close();System.exit(0);

}}

IOException (error) must be thrown from main or handle in side

this method

Example – Reading a text fileimport java.io.*;

public class FileExample{public static void main (String[] args) throws IOException {

File inFile = new File("e:\\Temp\\data.dat");FileReader fileReader = new FileReader(inFile);BufferedReader bufferReader = new

BufferedReader(fileReader);String inputStr;

inputStr = bufferReader.readLine();while (inputStr != null) {

System.out.println(inputStr);inputStr = bufferReader.readLine();

} // end of while

bufferReader.close();System.exit(0);

}}

Steps 1-3

Example – Reading a text fileimport java.io.*;

public class FileExample{public static void main (String[] args) throws IOException {

File inFile = new File("e:\\Temp\\data.dat");FileReader fileReader = new FileReader(inFile);BufferedReader bufferReader = new

BufferedReader(fileReader);String inputStr;

inputStr = bufferReader.readLine();while (inputStr != null) {

System.out.println(inputStr);inputStr = bufferReader.readLine();

} // end of whilebufferReader.close();System.exit(0);

}}

Step 4 in a while loop

Example – Reading a text fileimport java.io.*;

public class FileExample{public static void main (String[] args) throws IOException {

File inFile = new File("e:\\Temp\\data.dat");FileReader fileReader = new FileReader(inFile);BufferedReader bufferReader = new

BufferedReader(fileReader);String inputStr;

inputStr = bufferReader.readLine();while (inputStr != null) {

System.out.println(inputStr);inputStr = bufferReader.readLine();

} // end of whilebufferReader.close();System.exit(0);

}}

Step 6

Result

Write data to a text fileStep 1: Create a File object Step 2: Create a FileOutputStream

objectStep 3: Create a PrinterWriter objectStep 4: Write line(s)Step 5: Close the file

Create a FileOutputSTream and

PrintWriter objects• How to create a FileOutputStream objects:

FileOutputStream <variable_name> = new FileOutputStream(<name of a File object>);

• How to create a PrintWriter objectPrintWriter <variable_name> = new

PrintWriter(<name of a FileOutputStream object>);

• How to write a string to a file<A print writer object>.println(<string object name>);

More details on this link

Exampleimport java.io.*;

public class OutputExample{public static void main (String[] args) throws IOException {

File inFile = new File("e:\\Temp\\output.dat");FileOutputStream fileStream = new FileOutputStream(inFile);PrintWriter printWriter = new PrintWriter(fileStream);String inputStr;

int number[] = new int[10];for (int i=0;i<number.length; i++) {

number[i] = i+1;printWriter.println(number[i]);

}printWriter.close();System.exit(0);

}}

Exampleimport java.io.*;

public class OutputExample{public static void main (String[] args) throws IOException {

File inFile = new File("e:\\Temp\\output.dat");FileOutputStream fileStream = new FileOutputStream(inFile);PrintWriter printWriter = new PrintWriter(fileStream);String inputStr;

int number[] = new int[10];for (int i=0;i<number.length; i++) {

number[i] = i+1;printWriter.println(number[i]);

}printWriter.close();System.exit(0);

}}

Step 1-3

Exampleimport java.io.*;

public class OutputExample{public static void main (String[] args) throws IOException {

File inFile = new File("e:\\Temp\\output.dat");FileOutputStream fileStream = new FileOutputStream(inFile);PrintWriter printWriter = new PrintWriter(fileStream);String inputStr;

int number[] = new int[10];for (int i=0;i<number.length; i++) {

number[i] = i+1;printWriter.println(number[i]);

}printWriter.close();System.exit(0);

}}

Step 4(in for loop)

Exampleimport java.io.*;

public class OutputExample{public static void main (String[] args) throws IOException {

File inFile = new File("e:\\Temp\\output.dat");FileOutputStream fileStream = new FileOutputStream(inFile);PrintWriter printWriter = new PrintWriter(fileStream);String inputStr;

int number[] = new int[10];for (int i=0;i<number.length; i++) {

number[i] = i+1;printWriter.println(number[i]);

}printWriter.close();System.exit(0);

}}

Step 5(close file)

Just in time review1. Two steps must occur before we

can read data from a file:

and

A.Associate it to a fileB.Create a File object

Just in time review2. The following two statements will

associate file 1 and file2 to the same file:File file1 = new File(“c:\\one”,”two.dat”);File file2 = new File (“C:\\one\\two.dat”)A. TrueB. False

top related