Difference between revisions of "CIS 3020 Part 9"

From In The Wings
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 09: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

  1. If first < last then begin
  2. Partition the elements in the subarray first..last so that the pivot value is in place (in position pivIndex)
  3. Apply quickSort to the first subarray first..pivIndex-1
  4. Apply quickSort to the second subarray pivIndex-1..last

The two stopping cases are:

  1. (first = last) -- Only one value in subarray so sorted
  2. (first > last) -- no values in subarray so sorted

How do we partition?

  1. Define the pivot value as the contents of val[first]
  2. Initialize up to first and down to last
  3. Repeat 4-6 until up meets or passes down
  4. Increment up until up selects the first element greater than the pivot value
  5. Decrement down until it selects the first element less than the pivot value
  6. If up < down exchange their values
  7. Exchange val[first] and val[down]
  8. Define pivIndex as down