Lec 35 Java Fundamental of Computing
Lec 35 Java Fundamental of Computing
I Semester 2008-09
Lecture 35
1
Reminder : did you solve “Tower of Hanoi” problem
2
Design a method Tower of Hanoi(n)
which prints the detailed instruction about the movement of discs in order to
transfer n discs from A to B .
3
Input Output from/to Console : Lecture 34
Classes used :
• InputStreamReader
• BufferedReader
An interactive program for sorting numbers
file selection sort i.java
4
Input Output from/to File - without buffers
5
Input Output from/to File - without buffers
Classes used :
• FileReader
• FileWriter
Example : copying a file to another file.
6
Output to a File - with buffers
Printing a String at a time
Classes used :
• FileWriter
• PrintWriter
Example : Storing random number in a file.
7
Input from a File - with buffers
reading a line at a time
Classes used :
• FileReader
• BufferedReader
Example : Reading numbers from a file.
8
Selection Sort
int index_of_smallest_value(int[] A,int i)
//returns integer j such that A[j] is smallest among A[i], A[i+1],...
SelectionSort(int [] A)
{
for(int count=0;count<A.length;count=count+1)
{
int j = index_of_smallest_value(A, count);
if(j != count)
swap_values_at(A,j,count);
}
}
discussed in some earlier lecture
9
Quick Sort
10
Partitioning an array into two parts
A ... x ...
<x >x
Can be easily done using an extra array
11
Partitioning an array into two parts
A ... x ...
<x >x
Can be easily done using an extra array
12
Partitioning an array into two parts
Write a method
13
Partitioning
Write a method
14
Partitioning without using extra array
15
Partitioning without using extra array
NSE index is abbreviation for Index of Next Smaller Element. This variable
stores the index of array where we are going to store the next element ≤ x.
16
Quick Sort
17
Quick Sort
18
Quick Sort
19
Quick Sort
20
Quick Sort
21
Quick Sort
You can observe that the size of problem corresponding to recursive calls
decreases always. Hence the program will eventually terminate.
22
Show execution of Qsort on an array of 8 elements
23
Comparing Selection Sort and Quick Sort
for(n=2000,n<25000;n=n+1000)
{ Generate an array A of size n;
Fill it with random integers;
Create copy B of array A;
Execute Quick sort on A and measure time.
Execute SelectionSort on B and measure time.
}
24
Measuring time taken a method M
25
Comparing Selection Sort and Quick Sort
26