排序

public class Sort{
	public void swap(int[] array, int i, int j){       //简单的本地交换函数;
		int temp = array[i] ;
		array[i] = array[j] ;
		array[j] = temp ;
	}

	public void bubbleSort(int[] array){               //冒泡排序;
		int len = array.length ;
		for(int i=1;i<len;i++){
			for(int j=0;j<len-i;j++){
				if(array[j]>array[j+1]){
					swap(array,j,j+1) ;
				}
			}
		}
	}

	public void insertSort(int[] array){              // 插入排序;
		int len = array.length ;
		for(int i=1;i<len;i++){
			for(int j=i;j>0;j--){
				if(array[j]<array[j-1]){
					swap(array,j,j-1) ;
				}
			}
		}
	}

	public void chooseSort(int[] array){               //选择排序;
		int len = array.length ; 
		for(int i=0;i<len-1;i++){
			int min = i ;
			for(int j=i+1;j<len;j++){
				if(array[min]>array[j]){
					min = j ;
				}
				swap(array,min,i) ;
			}
		}
	}

	public void quickSort(int[] array){            //快速排序;
		QSort(array,0,array.length-1) ;
	}
	public void QSort(int[] array, int left, int right){
		if(left<=right){
			int i = left ;
			int j = right ;
			int temp = array[left] ;
			while(i!=j){
				while(j>i && array[j]>=temp){
					j-- ;
				}
				while(j>i && array[i]<=temp){
					i++ ;
				}
				if(i<j){
					swap(array,i,j) ;
				}else{
					swap(array,i,left) ;
					QSort(array,left,i-1) ;
					QSort(array,i+1,right) ;
				}
			}					
		}
	}

	int[] tempArray ;
	public void mergeSort(int[] array){                 //归并排序;
		tempArray = new int[array.length] ;
		MSort(array,0,array.length-1) ;
	}
	public void MSort(int[] array, int left, int right){
		if(left<right){
			int center = (left + right)/2 ;
			MSort(array,left,center) ;
			MSort(array,center+1,right) ;
			Merge(array,left,center+1,right) ;
		}else{
			return ;
		}
	}
	public void Merge(int[] array,int lpos,int rpos, int rightEnd){		
		int leftEnd = rpos - 1 ;
		int i = lpos ;
		int j = rpos ;
		int k = lpos ;
		while(i<=leftEnd && j<=rightEnd){
			if(array[i]<=array[j]){
				tempArray[k] = array[i] ;
				i++ ;
				k++ ;
			}else{
				tempArray[k] = array[j] ;
				k++ ;
				j++ ;
			}
		}
		while(i<=leftEnd){
			tempArray[k] = array[i] ;
			k++ ;
			i++ ;
		}
		while(j<=rightEnd){
			tempArray[k] = array[j] ;
			k++ ;
			j++ ;
		}
		int len = rightEnd - lpos + 1 ;
		for(int l=0;l<len;l++){
			array[rightEnd] = tempArray[rightEnd] ;
			rightEnd-- ;
		}
	}

	public static void main(String[] args){           //测试;
		Sort s = new Sort() ;
		int[] array = {9,8,7,6,5,4,3,2,1} ;
		//s.bubbleSort(array) ;
		//s.quickSort(array) ;
		s.mergeSort(array) ;
		//s.insertSort(array) ;
		//s.chooseSort(array) ;
		for(int i=0;i<array.length;i++){
			System.out.print(array[i] + " ") ;
		}

	}
}

  

转载于:https://www.cnblogs.com/lshl/p/5926056.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值