Introduction and implementation of common algorithms

1. Selective sorting
Selective sorting is a basic and stable sorting algorithm. It compares the first element V1 with all other elements one by one, compares the smallest element Vmin, and exchanges the array subscript positions of V1 and Vmin; The second one is compared with all the remaining elements..., so that the entire array is compared in a loop to get an ordered array. The time complexity is n to the second power.
Implementation code (java):

    public static void xuanze_sort(){
        int data []={1,3,2,22,33,4,6,5};
        for(int i=0;i<data.length;i++){
            for(int j=i+1;j<data.length;j++){
                if(data[i]>data[j]){
                    int temp=data[j];
                    data[j]=data[i];
                    data[i]=temp;
                }
            }
        }
        for (int t : data) {
            System.out.println(t);
        }
    }

2. Bubble sorting
Bubble sorting is also a common sorting algorithm. By comparing and exchanging adjacent elements, first find the largest element and put it at the end of the array, and then compare the second largest element..., Thus, the entire ordered array can be compared in a loop. The time complexity is n to the second power.
Implementation code (java):

    public static void maopao_sort() {
        int data[] ={2,1,5,4,33,3,6};
        for(int i=0;i<data.length-1;i++){
            for(int j=0;j<data.length-1-i;j++){
                if(data[j]>data[j+1]){
                    int temp=data[j];
                    data[j]=data[j+1];
                    data[j+1]=temp;
                }
            }
        }
        for (int t : data) {
            System.out.println(t);
        }
    }

3.
Binary search algorithm, also called binary search, is widely used in the underlying technologies of various open source frameworks, such as database indexes.
Method to realize:

   //二分查找,对有序数组快速查找其中的某个元素的下标,时间复杂度为log2n
//    如果能找到元素则返回元素对应的下标,否则返回-1
    public static int half_find(int []arr,int key){
        int low =0;
        int high=arr.length-1;
        int middle=0;
        if(key<arr[low] || key>arr[high] || arr.length==0){
            //未找到或数组为空
            return -1;
        }
        while(low<=high){
            //中间下标
            middle=(high+low)/2;
            if(key>arr[middle]){
                low=middle+1;
            }else if (key<arr[middle]){
                high=middle-1;
            }else{
                return middle;
            }
        }
        return -1;
    }

Guess you like

Origin blog.csdn.net/qq_39719415/article/details/107916191