java 选择排序、冒泡排序、折半查找

public class SortAndSelectDemo{
	public static void main(String[] args){
		int[] arr = {3, 5, 17, 2, 11, 13, 19, 7, 23};
		//bubbleSort(arr);
		selectSort(arr);
		printArr(arr);
		int searchIndex = halfSearch(arr,6);
		System.out.println(searchIndex);
	}
	
	//选择排序
	public static void selectSort(int[] arr){
		for(int i = 0; i < arr.length-1; i++){
			for(int j = i+1; j < arr.length-1; j++){
				if(arr[i] > arr[j]){
					int temp = arr[i];
					arr[i] = arr[j];
					arr[j] = temp;
				}
			}
		}
	}
	
	//冒泡排序
	//外循环:对比n-1次,内循环:n-1次随i递减
	public static void bubbleSort(int[] arr){
		for(int i = 0; i < arr.length-1; i++){
			for(int j = 0; j < arr.length-1-i; j++){
				if(arr[j] > arr[j+1]){
					int temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
	}
	
	//折半查找
	public static int halfSearch(int[] arr, int searchNum){
		int minIndex = 0;
		int maxIndex = arr.length;
		int midIndex = 0;
		while(minIndex < maxIndex){
			midIndex = (minIndex + maxIndex)/2;
			if(arr[midIndex] > searchNum){
				maxIndex = midIndex-1;
			}else if(arr[midIndex] < searchNum){
				minIndex = midIndex + 1;
			}else{
				return midIndex;
			}
		}
		return -1;
	}
	
	public static void printArr(int[] arr){
		System.out.print("[");
		for(int i = 0;i < arr.length; i++){
			if(i == arr.length-1){
				System.out.println(arr[i] + "]");
			}else{
				System.out.print(arr[i] + "\t");
			}
		}
	}
}

  选择排序:

冒泡排序:

 

posted @ 2018-11-19 15:24  SasaL  Views(326)  Comments(0Edit  收藏  举报