数组常见的排序算法

冒泡排序

public class Test001 {

	public static void bubbleSort(int[] a) { //通过冒泡法将一组数由从大到小或者从小到大排序
		for (int i = 0; i < a.length - 1; i++) {   
			for (int j = 0; j < a.length - i -1; j++) {
				if(a[j] > a[j + 1]){         //将连续两个数进行比较,根据排序的需求进行交换
					int temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp; 
				}
			}
		}
	}
	
	public static void show(int[] a){    //遍历数组
		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i]);
		}
	}
	public static void main(String[] args) {

		int[] a = {1,3,5,2,8,4};
		bubbleSort(a);
		show(a);
	}
}

选择排序


public class Test002 {

	public static void selectSort(int a[]){
		for (int i = 0; i < a.length - 1; i++) {       //要比较的趟数
			int index = i;                             //定义一个用来比较的位置
			for (int j = i + 1; j < a.length; j++) {   //循环进行比较,并交换位置
				if(a[j] > a[index]){
					index = j;
				}
			}
			if(index != i){      //将数值进行交换,从而使每一位在当前状态都是最大值/最小值
				int temp = a[i];
				a[i] = a[index];
				a[index] = temp;
			}
		}
	}

	public static void show(int[] a){
		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i]);
		}
	}
	
	public static void main(String[] args) {

		int[] a = {1,3,5,2,8,4};
		selectSort(a);
    	show(a);
    }
}

有序插入

public class Test003 { //给一个有序数列插入一个数,插入后任使其有序

	public static int[] insertSort(int[] a,int num){
		int index = a.length;
		for (int i = 0; i < a.length; i++) {      //查找到要插入数字的位置
			if(num < a[i]){
				index = i;
				break;
			}
		}
		int[] b = new int[a.length + 1];      //创建一个长度为旧数组长度+1的新数组
		for (int i = 0; i < index; i++) {     //后续赋值即可
			b[i] = a[i];
		}
		b[index] = num;
		for (int i = index + 1; i < b.length; i++) {
			b[i] = a[i -1];
		}
		return b;
	}

	public static void show(int[] a){
		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i]);
		}
	}
	public static void main(String[] args) {

		int[] a = {1,13,25,36,57};
		a = insertSort(a,33);
		show(a);
	}

}

二分查找法

public class Test004 {

	public static int halfFind(int[] a, int num){
		int low = 0;                  //定义一个低位在第0为
		int index = -1;               //声明一个位置并给赋值为-1
		int high = a.length -1;       //定义一个高位为数组最后一位即数组长度-1
		while(high >= low) {          //当满足高位大于等于低位则进行循环
			if(num  == a[(low + high)/2]){    
				index = (low + high)/2;
				return index;
			}
			if(num < a[(low + high)/2]){
				low = (low + high)/2 + 1;       //改变低位的位置,使其变为判定位置的后一位
			}
			if(num > a[(low + high)/2]){        ////改变高位的位置,使其变为判定位置的前一位
				high = (low + high)/2 - 1;
			}
		}
		return index;
	}

	public static void main(String[] args) {

		int[] a = {89,78,63,52,29,12};
		int num = halfFind(a,7);
		System.out.println(num);
	}
}

你可能感兴趣的:(排序算法)