java的冒泡排序、选择排序与插入排序与二分查找

排序思想:
	1.冒泡排序:
	 2.选择排序:
	 3.插入排序:
	 4.二分查找法:
import java.util.*;
public class SortDemo {
	public static void main(String[] args){
		//testArray();
		binarySerach();
		/*int a[] = new int[]{6,2,1,0,8,9};
		insertSort(a);
		System.out.println(Arrays.toString(a));*/
	}
	public static void testArray(){
		final int N = 50000;
		int[] b = new int [N];
		int[] c = new int [N];
		int[] d = new int [N];
		for (int i = 0; i < N; i++){
			b[i] = (int)(Math.random() * 100000);
			c[i] = b[i];
			d[i] = c[i];
		}
		//冒泡排序效率
		long startTime1 = System.currentTimeMillis();
		bubbleSort(b);
		long endTime1 = System.currentTimeMillis();//1970年1月1号 0时0分0秒
		System.out.println("冒泡排序总共耗时:" + (endTime1 - startTime1));
		
		//选择排序效率
		startTime1 = System.currentTimeMillis();
		selectSort(c);
		endTime1 = System.currentTimeMillis();
		System.out.println("选择排序总耗时:" + (endTime1 - startTime1));
		
		//调用Arrays.sort()方法
		startTime1 = System.currentTimeMillis();
		insertSort(d);
		endTime1 = System.currentTimeMillis();
		System.out.println("插入排序总耗时:" + (endTime1 - startTime1));
	}
	/**
	* 冒泡排序(如果前一个数大于后面一个数,交换位置)
	*/
	public static void bubbleSort(int[] a){
		int temp;
		for (int i = 0; i < a.length - 1; i++){//循环的次数
			//比较值大小,如果前一个数大于后面一个数,交换位置
			for (int j = 0; j < a.length - 1 - i; j++){
				if (a[j] > a[j + 1]){
					temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;
				}
			}
		}
	}
	/**
	* 选择排序
	*/
	public static void selectSort(int[] a){
		int minIndex;//最小值的索引
		for (int i = 0; i < a.length; i++){//循环的次数
			minIndex = i;
			//每次循环记录最小数字的索引(下标)
			for (int j = i + 1; j < a.length; j++){
				if (a[j] < a[minIndex]){
					minIndex = j;
				}
			}
			//需要把最小的数放到a[i],
			int temp = a[minIndex];
			a[minIndex] = a[i];
			a[i] = temp;
		}
	}
	/**
	* 插入排序
	*/
	public static void insertSort(int[] a){
		for (int i = 0; i < a.length; i++){
			for (int j = i; j > 0; j--){
				if (a[j - 1] > a[j]){
					int temp = a[j];
					a[j] = a[j - 1];
					a[j - 1] = temp;
				}
			}
		}
	}
	
	/**
	* 二分查找法前提:已经完成排序的数组
	*/
	public static void binarySerach(){
		int a[] = new int[]{1, 3, 5, 8, 10, 16, 20};
		int low = 0;
		int mid = 0;
		int high = a.length;
		Scanner sc = new Scanner(System.in);
		int s = sc.nextInt();
		//for (int i = 0; i < a.length; i++){//没找到循环的次数比下面用while循环要多
		int flag = 0;
		while (low <= high){
			flag++;
			mid = (low + high) / 2;
			if (a[mid] == s){
				System.out.println("找到了" + flag);
				break;
			} else if (a[mid] > 3){
				high = mid - 1;
			} else {
				low = mid + 1;
			}
		}
		System.out.println(flag);
	}
}













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值