java常用的几种排序(冒泡排序 选择 插入排序 /快速排序)

时间:2021-04-13 22:06:40
package pakage1;

public class quickSo {
	public static void main(String[] args) {
		int[] a = {34,3,53,2,23,7,14,10};
		//冒泡排序
		bubblingSort(a);
		//选择
		changeSort(a);
		//插入排序
		insertSort(a);
		//快速排序
		quiteSort(a);
		
	}
	//快速
	public  static void quiteSort(int[] a) {
		if(a.length>0){
			quite(a,0,a.length-1);
		}
		for(int i=0;i<a.length;i++){
			System.out.print(a[i]+" ");
		}
		System.out.println("");
	}
	public  static void quite(int[] a, int low, int hight) {
		if(low<hight){
			int middle = getMiddle(a,low,hight);
			quite(a, low, middle-1);
			quite(a, middle+1, hight);
		}
				
	}
	public static int getMiddle(int[] a, int low, int hight) {
		int tmp = a[low];
		while(low < hight){
			while(low < hight && a[hight]>tmp){
				hight --;
			}
			a[low] = a[hight];
			while(low < hight && a[low]<=tmp){
				low ++;
			}
			a[hight] = a[low];
			a[low] = tmp;
		}
		return low;
	}
	//冒泡
	public static void bubblingSort(int[] a) {
		for(int i=0;i<a.length-1;i++){
			for(int j=i+1;j<a.length;j++){
				int tmp =a[i];
				if(a[j]<a[i]){
					a[i] = a[j];
					a[j] = tmp;
				}
			}
		}
		for(int i=0;i<a.length;i++){
			System.out.print(a[i]+" ");
		}
		System.out.println("");
	}
	//选择
	public static void changeSort(int[] a){
		for (int i = 0; i < a.length; i++) {
			int k = i;
			for(int j=i+1;j<a.length;j++){
				if(a[j]<a[k]){
					k=j;
				}
				while (k!=i) {
					int t = a[i];
					a[i] = a[k];
					a[k] = t;
				}
			}
		}
		for(int i=0;i<a.length;i++){
			System.out.print(a[i]+" ");
		}
		System.out.println("");
	}
	
	//插入排序
	public static void insertSort(int[] a){
		for(int i=1;i<a.length;i++){
			int tmp = a[i];
			int j = i;
			while(a[j-1]>tmp){
				a[j] = a[j-1];
				j--;
				if (j<=0) {
					break;
				}
			}
			a[j] = tmp;
		}
		for(int i=0;i<a.length;i++){
			System.out.print(a[i]+" ");
		}
		System.out.println("");
	}
}

图片是输出结果

java常用的几种排序(冒泡排序 选择 插入排序 /快速排序)