- Threaded implementation of Quick Sort - ConcurrentQSort
- import java.io.*;
- import java.util.*;
- import java.lang.Math;
- /**
- *
- */
- interface ISort {
- abstract void quickSort(Comparable[] a, int left, int right);
- abstract void quickSort(Comparable[] a);
- }
- public class QSort implements ISort {
- public static void main(String[] args) {
- QSort QSob = new QSort();
- Integer[] aInts = {51, 34, 54, 26, 74, 67, 68, 29, 2, 8, 45};
- QSob.quickSort(aInts,0,10);
- System.out.println("Sorted Integers:");
- System.out.println();
- String[] aStrings = {"paisley", "ayr", "hamilton", "dumfries", "anywhere you like"};
- QSob.quickSort(aStrings,0,4);
- System.out.println("Sorted Strings:");
- System.out.println();
- }
- public void quickSort(Comparable[] a) {
- try {
- int p = partition(a, 3);
- for(int i = p ; i <a.length ; i++) {
- //a[i] = a[i];
- Arrays.sort(a);
- System.out.println(a[i]+ " ");
- }
- }
- catch(NullPointerException e) {
- System.out.println( "Null Pointer Excetption ");
- }
- }
- private int partition(Comparable[] a,int left) {
- Comparable pivot = a[left]; int p = left;
- for (int r = left+1; r <= a.length - left; r++) {
- @SuppressWarnings("unchecked")
- int comp = a[r].compareTo(pivot);
- if (comp < 0) {
- a[p] = a[r]; a[r] = a[p+1]; a[p+1] = pivot;
- p++;
- }
- }
- return p;
- }
- public void quickSort(Comparable[] a, int left, int right) {
- if (left < right) {
- int p = partition(a, left, right);
- quickSort(a, left, p-1);
- quickSort(a, p+1, right);
- }
- }
- private int partition(Comparable[] a,int left, int right) {
- // Partition a[left…right] such that a[left…p-1] are all less than
- // or equal to a[p] and a[p+1…right] are all greater than or equal to
- // a[p].
- Comparable pivot = a[left]; int p = left;
- for (int r = left+1; r <= right; r++) {
- @SuppressWarnings("unchecked")
- int comp = a[r].compareTo(pivot);
- if (comp < 0) {
- a[p] = a[r]; a[r] = a[p+1]; a[p+1] = pivot;
- p++;
- }
- }
- return p;
- }
- }
- Q : queue
- A : array
- process qrunner
- while not done do // need to define this condition
- (i,j) = Q.get()
- while i < j do
- p = pivot(i,j)
- k = partition(i,j,p)
- if k+1 < j then Q.add((k+1,j))
- j = k-1
- end
- procedure quicksort(i,j, N)
- Q.add(i,j)
- startPool(N, qrunner)
- end