首页 > 代码库 > 排序算法整合(冒泡,插入,选择,归并算法)

排序算法整合(冒泡,插入,选择,归并算法)

package com.hcj.test;

public class PaiXu {
	public static void main(String[] args) {
		/*int[] a = {33 , 22, 8, 17, 17, 18, 65, 44, -3, -5};
		选择排序
		int[] result = xuanZePaiXu(a);
		冒泡排序
		int[] result = maoPaoPaiXu(a);
		插入排序
		int[] result = chaRuPaiXu(a);*/
		
		//归并排序
		int[] t1 = {-1, 3, 7, 9, 11, 19, 55};
		int[] t2 = {-7, 1, 2, 10, 11, 18};
		int[] result = guiBingPaiXu(t1, t2);
		
		for (int i = 0; i < result.length; i++) {
			System.out.println(result[i]);
		}
	}
	
	
	//选择排序
	public  static int[] xuanZePaiXu(int[] a){
		for(int i = 0; i < a.length; i++){
			for(int j = i + 1; j < a.length - 1; j++){
				if(a[i] > a[j]){
					int temp = a[i];
					a[i] = a[j];
					a[j] = temp;
				}
			}
		}
		return a;
	}
	
	//冒泡排序
	public static int[] maoPaoPaiXu(int[] a){
		for(int i = 0; i < a.length; i++){
			for (int j = 0; j < a.length - i; j++) {
				if(a[j] > a[j+1]){
					int temp = a[j];
					a[j] = a[j+1];
					a[j+1] = temp; 
				}
			}
		}
		return a;
	}	
	
	//插入排序
	public static int[] chaRuPaiXu(int[] a){
		int base = 0, compare = 0, temp;
		//当数据小于前一个,则插入前方,否则插入后方
		for(base = 1; base < a.length; base++){
			temp = a[base];
			compare = base;
			while(compare > 0 && a[compare - 1] > temp){
				//如果待比较数比前一个数小,则将前一个数向后挪一位
				a[compare] = a[compare - 1];
				compare--;
			}
			a[compare] = temp;
		}
		return a;
	}
	
	//归并排序
	public static int[] guiBingPaiXu(int[] a, int[] b){
		int size1 = a.length;
		int size2 = b.length;
		int arg1 = 0, arg2 = 0, arg3 = 0;
		int[] c = new int[size1 + size2];
		for(arg3 = 0; arg3 < size1 + size2; arg3++){
			if(arg2 == size2){
				c[arg3] = a[arg1];
				arg1++;
			}else if(arg1 == size1){
				c[arg3] = b[arg2];
				arg2++;
			}else if(a[arg1] < b[arg2]){
				c[arg3] = a[arg1];
				arg1++;
			}else if(a[arg1] >= b[arg2]){
				c[arg3] = b[arg2];
				arg2++;
			}
			System.out.println("值为" + c[arg3]);
		}
		return c;
	}
	
	
}

排序算法整合(冒泡,插入,选择,归并算法)