Presentation is loading. Please wait.

Presentation is loading. Please wait.

Selection sort and Merge sort File input/output. HW 2 – Section 02 Avg = 96/100.

Similar presentations


Presentation on theme: "Selection sort and Merge sort File input/output. HW 2 – Section 02 Avg = 96/100."— Presentation transcript:

1 Selection sort and Merge sort File input/output

2 HW 2 – Section 02 Avg = 96/100

3 HW 2 – Section 01 Avg = 89/100

4 HW2 Answers 1. The difference between the two String methods: equals and equalsIgnoreCase is A. equals compares two string objects, and ignores case considerations b. equalsIgnoreCase compares two string objects, and ignores case considerations c. both equals and equalsIgnoreCase compare two string objects and ignore case considerations. D. both equals and equalsIgnoreCase compare two string objects and consider cases

5 HW2 Answers 2. In order to determine how many characters contained in a String object myString, we use: a. myString.size() b. myString.size c. myString.length d. myString.length()

6 HW2 Answers 3. 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) {….}

7 HW2 Answers 4. Fixed-size array declaration has two limitations: inability to handle an overflow situation and possible under utilization of allocated space a. True b. False

8 HW2 Answers 5. 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 attribute b. A parameter c. A return value d. A return data type

9 HW2 Answers 6. 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( );

10 HW2 Answers 7. 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];

11 HW2 Answers 8. 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 256 b. 0 and 256 c. 1 and 8 d. 0 and 8

12 HW2 Answers 9. 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 256 b. 0 and 256 c. 1 and 8 d. 0 and 8

13 HW2 Answers 10. 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

14 HW2 Answers Matching 11. public void setExchangeRate (double rate) { exchangeRate = rate; } CBE A D

15 HW2 Answers Matching 12. B DF AG CE

16 HW2 Answers Matching 12. B DF A C E G

17 HW2 Answers Matching –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 = ; C D AEB

18 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 search B.Linear search

19 HW2 Answers 15. 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.

20 HW2 Answers 16. public String ClassB( ) { description = “Unknown”; return description; } 1.String should be removed because Constructors don’t need return data type 2. Return description should also be removed because constructors should not return anything.

21 HW2 Answers 17. CurrencyConverter converter = new CurrencyConverter(); double amount = converter.feeRate; 1.feeRate is a private attribute and therefore is not assessible outside of CurrencyConverter class.

22 HW2 Answers 18. 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

23 HW2 Answers 19 obj = new QuestionOne(); // => amount =10 Obj.setAmount(0.15); // =>amount = 10*(0.15+1) = 10*1.15 = 11.50 Updated amount is 11.50

24 HW2 Answers 20 resultStr=“Spring Break" lengthStr =12

25 Selection Sort public void selectionSort(int[] number) { int minIndex, size, temp; size = number.length;

26 Selection Sort for (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; }

27 Selection Sort i=0: minIndex=0 j= 1 number[1]=20 > number[0]=18 j=2 number[2]=17 < number[0]=18 minIndex = 2 j=3 number[3]=40 > number[2]=17 j=4 number[4]=22 > number[2]=17 j=5 number[5]=27 > number[2]=17 j=6 number[6]=30 > number[2]=17 Number 40201817222730 0 1 2 3 4 5 6

28 Selection Sort i=0: minIndex=2 temp= number[0] = 18 number[0]=number[2] = 17 number[2] = temp = 18; Number 40201817222730 0 1 2 3 4 5 6

29 Selection Sort i=0: minIndex=2 temp= number[0] = 18 number[0]=number[2] = 17 number[2] = temp = 18; Number 40201718222730 0 1 2 3 4 5 6

30 Selection Sort i=1: minIndex=1 j=2 number[2]=18 < number[1]=20 minIndex = 2 j=3 number[3]=40 > number[2] = 18 j=4 number[4]=22 > number[2]=18 j=5 number[5]=27 > number[2]=18 j=6 number[6]=30 > number[2]=18 Number 40201718222730 0 1 2 3 4 5 6

31 Selection Sort i=1: minIndex=2 temp= number[1] = 20 number[1]=number[2] = 18 number[2] = temp = 20; Number 40201718222730 0 1 2 3 4 5 6

32 Selection Sort i=1: minIndex=2 temp= number[1] = 20 number[1]=number[2] = 18 number[2] = temp = 20; Number 40181720222730 0 1 2 3 4 5 6

33 Selection Sort i=2: minIndex=2 j=3 number[3]=40 > number[2] =20 j=4 number[4]=22 > number[2]=20 j=5 number[5]=27 > number[2]=20 j=6 number[6]=30 > number[2]=20 Number 40181720222730 0 1 2 3 4 5 6

34 Selection Sort i=2: minIndex=2 j=3 number[3]=40 > number[2] =20 j=4 number[4]=22 > number[2]=20 j=5 number[5]=27 > number[2]=20 j=6 number[6]=30 > number[2]=20 Number 40181720222730 0 1 2 3 4 5 6

35 Selection Sort i=3: minIndex=3 j=4 number[4]=22 < number[3]=40 minIndex = 4 j=5 number[5]=27 > number[4]=22 j=6 number[6]=30 > number[4]=22 Number 40181720222730 0 1 2 3 4 5 6

36 Selection Sort i=3: minIndex=4 temp= number[3] = 40 number[3]=number[4] = 22 number[4] = temp = 40; Number 22181720402730 0 1 2 3 4 5 6

37 Selection Sort i=4: minIndex=4 j=5 number[5]=27 < number[4]=40 minIndex=5 j=6 number[6]=30 > number[5]=27 Number 22181720402730 0 1 2 3 4 5 6

38 Selection Sort i=4: minIndex=5 temp= number[4] = 40 number[4]=number[5] = 27 number[5] = temp = 40; Number 22181720402730 0 1 2 3 4 5 6

39 Selection Sort i=5: minIndex=5 j=6 number[6]=30 < number[5]=40 minIndex=6 Number 22181720274030 0 1 2 3 4 5 6

40 Selection Sort i=5: minIndex=6 temp= number[5] = 40 number[5]=number[6] = 30 number[6] = temp = 40; Number 22181720274030 0 1 2 3 4 5 6

41 Selection Sort i=5: minIndex=6 temp= number[5] = 40 number[5]=number[6] = 30 number[6] = temp = 40; Number 22181720273040 0 1 2 3 4 5 6

42 Concepts 1.String class, methods for String class (length, substring,compareTo,indexOf…) Week 5 slides 2. Instantiable classes: Private/public attributes/methods Different between attribute and methods Constructors Parameters passing for methods Week 7-8 slides

43 Concepts 3. Array: Definition, how to declare an array, how to allocate memory, how to initialize values How much memory is needed for an array How to determine how many elements an array has Passing an array to a method (passing by reference) Week 9 slides

44 Concepts 4. Search and Sorting Linear Search Binary Search (Week 10-11)

45 Merge Sort Start=0, end = 6, mid=(6+0)/2 = 3 Number 40201817222730 0 1 2 3 4 5 6 20184017 222730

46 Merge Sort. Start=0, end = 3, mid=(3+0)/2 = 1. Start=4, end =6, mid=(4+6)/2=5 2018 2227 30 4017

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

48 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:

49 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);

50 Passing Array to Methods for(int i=0; i<number.length; i++) number[i] = i; anObj.changeArrayValue(number); 0123 4 1234 5 number

51 Final Exam Section 01: MWF begins 12:05- 12:55pm Monday, May 08, 2006. 3:15-5:15pm Section 02: MWF begins 1:10-2pm Wednesday, May 10, 2006: 1-3pm

52 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

53 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

54 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 = new File( ); OR File =new File(, );

55 File Class Go to http://java.sun.com/j2se/1.3/docs/a pi/java/io/File.html http://java.sun.com/j2se/1.3/docs/a pi/java/io/File.html See the constructors of File class FileFile(String pathname) Creates a new File instance by converting the given pathnameString string into an abstract pathname

56 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 test.dat in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname.

57 File myFile = new File(“C:\\mydocuments”,”sample.dat”); (Windows) File myFile = new File(“C:/mydocuments”,”sample.dat”); (Unix) Example (continue)

58 File I/O Low level I/OHigh level I/OText file I/O Treat a file As a set of bytes Treat A file As a set of data of primitive Data type Treat A file As a set of text (or String)

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

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

61 Low level data input Step 1: Create a File object Step 2: Create a FileInputStream objectFileInputStream Step 3: Declare an array to keep input data, allocate memory for this array Step 4: Read data and process data if neededRead data Step 5: Close the file

62 Sample: Low-Level File Input //set up file and stream File inFile = new File("sample1.data"); FileInputStream inStream = new FileInputStream(inFile); //set up an array to read data in int fileSize = (int)inFile.length(); byte[] byteArray = new byte[fileSize]; //read data in and display them inStream.read(byteArray); for (int i = 0; i < fileSize; i++) { System.out.println(byteArray[i]); } //input done, so close the stream inStream.close();

63 Low level data output Step 1: Create a File object Step 2: Create a FileOutputStream objectFileOutputStrea Step 3:Get data ready Step 4:Write data to output streamWrite data Step 5: Close the file

64 Sample: Low-Level File Output //set up file and stream File outFile = new File("sample1.data"); FileOutputStream outStream = new FileOutputStream( outFile ); //data to save byte[] byteArray = {10, 20, 30, 40, 50, 60, 70, 80}; //write data to the stream outStream.write( byteArray ); //output done, so close the stream outStream.close();

65 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

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

67 Sample Output import java.io.*; class Ch12TestDataOutputStream { public static void main (String[] args) throws IOException {... //set up outDataStream //write values of primitive data types to the stream outDataStream.writeInt(987654321); outDataStream.writeLong(11111111L); outDataStream.writeFloat(22222222F); outDataStream.writeDouble(3333333D); outDataStream.writeChar('A'); outDataStream.writeBoolean(true); //output done, so close the stream outDataStream.close(); }

68 Setting up DataInputStream A standard sequence to set up a DataInputStream object:

69 Sample Input import 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(); }

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

71 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

72 Read data from a text file Step 1: Create a File object Step 2: Create a FileReader objectFileReader Step 3: Create a BufferedReader objectBufferedReader Step 4: Read line by line Step 5: Convert String object to primitive data type as necessary Step 6: Close the file

73 Create FileReader and BufferedReader objects How to create a FileReader ojbect: FileReader = new FileReader( ); How to create a BufferedReaderobject: BufferedReader = new BufferedReader(<name of a FileReader object); How to read a line.readLine();

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

75 Example – Reading a text file import 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

76 Example – Reading a text file import 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

77 Example – Reading a text file import 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

78 Example – Reading a text file import 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); } Step 4 in a while loop

79 Example – Reading a text file import 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); } Step 6

80 Result

81 Write data to a text file Step 1: Create a File object Step 2: Create a FileOutputStream objectFileOutputStream Step 3: Create a PrinterWriter objectPrinterWrite Step 4: Write line(s) Step 5: Close the file

82 Create a FileOutputSTream and PrintWriter objects How to create a FileOutputStream objects: FileOutputStream = new FileOutputStream( ); How to create a PrintWriter object PrintWriter = new PrintWriter( ); How to write a string to a file.println( ); More details on this link

83 Example import 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); }

84 Example import 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

85 Example import 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)

86 Example import 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)

87 Just in time review 1. Two steps must occur before we can read data from a file: and A.Associate it to a file B.Create a File object

88 Just in time review 2. 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. True B. False


Download ppt "Selection sort and Merge sort File input/output. HW 2 – Section 02 Avg = 96/100."

Similar presentations


Ads by Google