//选择排序
public class SelectSort {
    public static void main(String[] args) {
        int [] arry = {3,1,6,2,5};
        for (int i = 0; i < arry.length -1; i++){
            int min = i;
            for(int j = i + 1; j < arry.length; j++){
                if(arry[j] < arry[min]){
                    min = j;
                }
            }
            // 如果min 不等于 i 等需要交换,
            if(min != i){
               int temp;
               temp = arry[min];
               arry[min] = arry[i];
               arry[i] = temp;
            }
        }
        for(int element:arry){
            System.out.println(element);
        }
    }
}
// 冒泡排序
public class BubbleSort {
    public static void main(String[] args) {
        int[] arry = {1,3,5,2,7,6,12,56};
        // 冒泡排序的核心:将左边的数和右边的数进行比较,当左边>右边时,交换位置,默认升序排序
        int count = 0;
        for (int i = 0; i < arry.length; i++){
            count ++;
            for (int j =  arry.length - 1; j > i; j--){
                if(arry[j-1] > arry[j]){
                    int tmp;
                    tmp = arry[j-1];
                    arry[j-1] = arry[j];
                    arry[j] = tmp;
                }
            }
        }
        System.out.println("比较次数: " + count);
        for (int element:arry){
            System.out.println(element);

        }
    }
}

  

二分法查找:

class BinarySearch {
    public static void main(String[] args) {
        int [] arry = {10,20,30,40,50,60};
        int index = binarySearch(arry, 30);
        System.out.println(index == -1 ? "该元素不存在": "改元素的下标 " + index);
    }
    public static int binarySearch(int[] arry, int dest){
        int begin = 0;
        int end = arry.length -1;
        while (begin < end){
            int mid = (begin + end) /2;
            if (arry[mid] == dest){
                return mid;
            }else if(arry[mid] < dest){
                begin = mid + 1;
            }else {
                end = mid  - 1;
            }
        }
        return -1;
    }
}

  

posted on 2021-01-06 09:17  风雨无阻!  阅读(34)  评论(0编辑  收藏  举报