Difference between revisions of "CIS 3020 Part 9"
Jump to navigation
Jump to search
Line 25: | Line 25: | ||
System.out.println(i1 + i2); | System.out.println(i1 + i2); | ||
</pre> | </pre> | ||
+ | ==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'' |
Revision as of 08:37, 27 April 2007
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