CIS 3020 Part 9
Contents
Command Line Arguments
- When you execute a Java program, you can provide values directly to the program
- These values are called "command line arguments" since they are in the command to execute your program:
java Print2CLArgs 123 hello
class Print2CLArgs {
public static void main (String[] arg) {
...
System.out.println(arg[0]);
System.out.println(arg[1]);
...
}
}
- Remember: the command line arguments are strings
- Suppose we execute:
java PrintSum 3 5 - And PrintSum contains:
System.out.println(arg[0] + arg[1]);
- What will be output?
35
- What you need to write is:
int i1 = Integer.parseInt(arg[0]); int i2 = Integer.parseInt(arg[1]); System.out.println(i1 + i2);
Quicksort
Algorithm
- If first < last then begin
- Partition the elements in the subarray first..last so that the pivot value is in place (in position pivIndex)
- Apply quickSort to the first subarray first..pivIndex-1
- Apply quickSort to the second subarray pivIndex-1..last
The two stopping cases are:
- (first = last) -- Only one value in subarray so sorted
- (first > last) -- no values in subarray so sorted
How do we partition?
- Define the pivot value as the contents of val[first]
- Initialize up to first and down to last
- Repeat 4-6 until up meets or passes down
- Increment up until up selects the first element greater than the pivot value
- Decrement down until it selects the first element less than the pivot value
- If up < down exchange their values
- Exchange val[first] and val[down]
- Define pivIndex as down
Heap Sort
To perform the heap sort we must:
- Create a heap (a tree with all nodes greater than their children)
- Remove the root elements from the heap one at a time, recomposing the heap
Code
public void heapSort(int[] val, int range) {
int k, curNode, child, temp;
boolean done;
formHeap (val, range);
for (k=range-1; k>=2; k--) {
curNode = 1;
child = 2;
done = false;
while ((child < k) && ( ! done)) {
if (child + 1 < k) {
if (val[child+1] > val[child]) {
child++;
}
if (val[curNode] >= val[child]) {
done = true;
} else {
temp = val[curNode];
val[curNode] = val[child];
val[child] = temp;
curNode = child;
child = curNode * 2;
}
}
}
}
}