欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Sort 博客分类: 数据结构 快速排序冒泡排序 

程序员文章站 2024-03-08 14:02:34
...
BubbleSort.Java

package sort;

public class BubbleSort {

    public static void main(String[] args) {
		int[] number={6,7,8,5,4,1,2,3};
//		bubbleSort(number);
		int low=0;
		int high=number.length-1;
	    quickSort(number,low,high);
		//print 
		for(int i=0;i<number.length;i++)
			System.out.print(number[i]+" ");				
	}
    //bubbleSort

	public static  void bubbleSort(int[] number) {	
		int tempt;
		boolean continueSort=true;
		while(continueSort){		
			continueSort=false;
			for(int i=0;i<number.length-1;i++){
				if(number[i]>number[i+1]){
					tempt=number[i+1];
					number[i+1]=number[i];
					number[i]=tempt;
					continueSort=true;				
				}			
			}		
		}
	}
	//recursion quickSort
	private static void quickSort(int[] number,int low,int high) {
	    if(low<high){//to identify whether this part has more than 1 numbers
	    	int pivotloc=Partition(number,low,high);
			quickSort(number,low,pivotloc-1);
			quickSort(number,pivotloc+1,high);	    	
	    }	
	}
	//Partition算法10.6(b)
	static int Partition(int[] number,int low,int high){
		int tempt=number[low];
		int pivotkey=number[low];
		while(low<high){
			while(low<high && number[high]>=pivotkey)
				high--;
			number[low]=number[high];
			while(low<high && number[low]<=pivotkey)
				low++;
			number[high]=number[low];		
		}
		number[low]=tempt;
		return low;	
	}	
}