`

优化的冒泡排序

 
阅读更多
	static int [] arr = new int []{ 4, 2, 3, 6,99, 5 ,56,23,41};
	public static void main(String[] args) {
		show(order1());

	}
	
	public static int[] order1(){
		int count = 0;
		boolean a = false;
		int temp = 0;
		for (int i = 0;i<arr.length-1;i++) {
			a = true;
			for (int j = 0; j < arr.length-i-1; j++) {
				count++;
				if(arr[j] > arr[j+1]){
					temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
					a = false;
				}
			}
			if(a){
				break;
			}
		}
		System.out.println(count);
		return arr;
	}
	
       //方向搜索,从数组的最后开始搜索到最前面
	public static int[] order1(){
		int count = 0;
		int temp = 0;
		for (int i = 0;i<arr.length - 1;i++) {
			for (int j = arr.length-1;j > i;j--) {
				if(arr[j] < arr[j-1]){
					temp = arr[j-1];
					arr[j-1] = arr[j];
					arr[j] = temp;
				}
			}
		}
		System.out.println(count);
		return arr;
	}
	public static void show(int [] arr){
		System.out.println(Arrays.toString(arr));
	}

    冒泡排序的思路:每次排序都找出数组当中最大的数(忽略已经找到的)然后放到数组最后面。可以加一个标志位来判断是是否已经完全拍好序了,以避免做无用功。可以看count的输出来判断是否增加了效率。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics