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

来源:互联网 发布:设a是2n 1阶矩阵 编辑:程序博客网 时间:2024/06/16 08:35
排序思想:
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