Java:快速排序(雙指針版)

import java.util.Arrays;

public class qucik_sort {

	public static void main(String[] args) {
		// TODO Auto-generated method stub 
		int[] scores={5,4,6,3,7,2,8,1,9,10};
		int[] scores1={4,2,3};
		//System.out.println(partition(scores,0,scores.length));
		System.out.println(Arrays.toString(quick_sort(scores,0,scores.length-1)));
		//System.out.println(Arrays.toString(quick_sort(scores1,0,scores1.length-1)));
	}
	public static int partition(int[] arrays,int p,int q){
		int x=arrays[p];
		int i=p;
		int tmp;
		int j=q;
		while(i <j){
			while(i<j && arrays[j]>=x){
				j--;}
			if(i<j){
					tmp=arrays[j];
					arrays[j]=arrays[i];
					arrays[i]=tmp;
					i++;
				}
			while(i<j && arrays[i]<=x){
				i++;}
			if(i<j){
					tmp=arrays[j];
					arrays[j]=arrays[i];
					arrays[i]=tmp;
					j--;
				}
				
			}
		
	
		return i;
	}


	public static int[] quick_sort(int[] arrays,int p,int q){
		if(p<q){
			int r=partition(arrays,p,q);
			//System.out.println(r+Arrays.toString(arrays));
			quick_sort(arrays,p,r-1);
			quick_sort(arrays,r+1,q);	
		
		}
		return arrays;
	}
}
相關文章
相關標籤/搜索