使用fok-join实现的快速排序

JDK7提供了fork-join框架,用该框架写了一个快速排序的实现。

 

 

public class QuickSort<T extends Comparable> extends RecursiveAction{
	
	private T[] array;
	
	/**
	 * start from 0
	 */
	private int start;
	
	/**
	 * end of the array,max value is array.length-1
	 */
	private int end;
	
	public QuickSort(T[] array,int start,int end){
		this.array = array;
		this.start = start;
		this.end = end;
	}
	
	private void swap(int a,int b){
		T tmp = array[a];
		array[a] = array[b];
		array[b] = tmp;
	}
	
	protected void compute() {
		if(this.start >= this.end)	return;
		
		int i = start+1;
		int j = end;
		
		for(;i < j;){
			if(array[i].compareTo(array[start]) <= 0){
				i++;
			}else{
				swap(i,j);
				j--;
			}
		}
		if(array[i].compareTo(array[start]) < 0)
		swap(start,i);
		
		invokeAll(new QuickSort(array, start, i-1),
				new QuickSort(array,i,end));
	}

	public static void main(String[] args){
		List<Integer> values = new ArrayList<Integer>();
		for(int i = 0; i < 100; i++)
			values.add(i);
		
		Collections.shuffle(values);
		
		Integer[] array = values.toArray(new Integer[0]);
		
		new ForkJoinPool().invoke(new QuickSort<Integer>(array, 0, array.length - 1));
		
		for(int i = 0; i < array.length; i++){
			System.out.print(array[i]+"  ");
		}
	}
}
 

你可能感兴趣的:(JOIN)