Java數據結構之快速排序

前言

     快速排序是面試中非常常見的排序算法,工作中,快速排序的效率也是我們常常用到的,他的發展來源於劃分算法,採用的是分治策略.


實現思路

  1.     先從數組中選擇一個pivot,
  2.     遍歷數組,講數組中比pivot大的數放到其右邊,比其小的放到左邊,
  3.     直到各區數組長度爲1之前,都回到1處執行

具體說明

如上所示,我們先選擇數組中第一個數49作爲pivot,在第一次劃分之後,會發現數組發生了變化,就是所有比pivot大的在右邊,小的在左邊

然後遞歸調用子數組劃分,直到子數組長度爲1.

代碼實現

package com.example.liner;


public class QuickSort {

	//
	public static int theArr[]=new int []{13,2,4,1,22,31,5,7,8,9,15,17};
	public static int partition=10;
	
	public static int partitionitSort(int leftPar,int rightPar,int pivot){
		int left=leftPar-1;
		int right=rightPar;
		
		while(true){
			while(
					theArr[++left]<pivot)
				;
			
			while(
					theArr[--right]>pivot)
				;
			
			if(left>=right){
				break;
			}else{
				swap(left, right);
			}
			
		}
		swap(left, rightPar);
		return left;
	}
			
		
	
	public static void display(){
		
		for(int i=0;i<theArr.length;i++){
			System.out.print(theArr[i]+" ");
		}
	}
	
	public static void ruicksout(int left,int right){
		if(right-left<=0){
			return;
		}else{
			int pivot=theArr[right];
			
			int par=partitionitSort(left, right, pivot);
			ruicksout(left, par-1);
			ruicksout(par+1,right);
			
		}
	}
	
	
	public static void swap(int a,int b){
		int temp;
		temp=theArr[a];
		theArr[a]=theArr[b];
		theArr[b]=temp;
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		ruicksout(0, theArr.length-1);
		
		display();
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章