Structure and Algorithm (04): Sorting Rules and Search Algorithm

Source code of this article: GitHub·click here || GitEE·click here

One, recursive algorithm

Recursion is a method that calls itself, passing in different variables each time it is called, which can make the code concise. Recursive algorithm in computer science refers to a method of solving problems by repeatedly decomposing problems into similar sub-problems. Recursive methods can be used to solve many computer science problems, so it is a very important one in computer science concept.

Basic case : printing data recursively;

public class M01_Recursion {
    public static void main(String[] args) {
        printNum(3);
    }
    private static void printNum (int num){
        if (num > 1){
            printNum(num-1);
        }
        System.out.println("num="+num);
    }
}

Recursion diagram :

Structure and Algorithm (04): Sorting Rules and Search Algorithm

Based on the characteristics of the stack structure, the recursive call will form the above structure. After all the recursive methods are successfully put on the stack, the stack action will be executed in turn and the data result will be printed.

In actual development, recursion is often used to approach tree structure problems, factorial algorithms, sorting search and other mathematical problems.

The condition of the recursive algorithm must be constantly close to the exit condition, otherwise it is easy to cause an infinite loop to cause a memory overflow exception.

Second, the sorting algorithm

Sorting algorithm is the operation of arranging a group of data records in increasing or decreasing order according to a specific sorting strategy; commonly used sorting algorithms: bubble sorting, selection sorting, insertion sorting, hill sorting, merge sorting, quick sorting, cardinality Sorting, etc.; sorting algorithm selection: different sorting services can be tested by multiple algorithms, with low complexity and short time-consuming priority use.

1. Bubble sort

By comparing the values ​​of adjacent elements in the sorting sequence in turn, if the reverse order is found, the exchange is performed, so that the element with the larger value is gradually moved from the front to the back. The name of the algorithm is because the smaller the element will slowly float through the sort exchange One end of the sequence is just like the bubbles of carbon dioxide in a carbonated drink will eventually rise to the top, hence the name bubble sort.

public class M02_Bubble {
    public static void main(String[] args) {
        int[] arr = {3,7,5,9,6};
        bubbleSort(arr);
        for (int num:arr){
            System.out.println(num);
        }
    }
    public static void bubbleSort(int[] arr) {
        // 声明临时变量
        int temp = 0;
        // 排序总趟数
        for (int i = 0; i < arr.length - 1; i++) {
            // 元素交换
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    // 位置交换
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

Core idea :

The number of elements in the sorting pass is the number of times to be processed in theory; the position exchange of each element requires a complete comparison, and the outer loop is controlled. The inner loop exchanges the positions of individual elements.

2. Choose sort

Selection and sorting principle: The smallest (or largest) element is selected from the data elements to be sorted for the first time, stored at the beginning of the sequence, and then the smallest (large) element is found from the remaining unsorted elements. Then put it at the end of the sorted sequence. And so on, until the number of all data elements to be sorted is zero.

public class M03_Selection {
    public static void main(String[] args) {
        int[] arr = {30,70,50,90,60};
        selectionSort(arr);
    }
    public static void selectionSort (int[] arr){
        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            int minData = arr[i];
            for (int j = i + 1; j < arr.length; j++) {
                // 假设最小值判断
                if (minData > arr[j]) {
                    // 交换小值
                    minData = arr[j];
                    // 重置 minIndex,递增
                    minIndex = j;
                }
            }
            // 最小值交换放在arr[0]位置
            if (minIndex != i) {
                arr[minIndex] = arr[i];
                arr[i] = minData ;
            }
            System.out.println("第"+(i+1)+"轮排序:"+Arrays.toString(arr));
        }
    }
}

Output result :

第1轮排序:[30, 70, 50, 90, 60]
第2轮排序:[30, 50, 70, 90, 60]
第3轮排序:[30, 50, 60, 90, 70]
第4轮排序:[30, 50, 60, 70, 90]

3. Insertion sort

The basic idea is to insert a record into an ordered list that has been sorted. Each time the first element is taken from the unordered list during the sorting process, it is compared with the ordered list elements in turn, and it is inserted into the ordered list. The appropriate position in the table sequence makes it a new ordered table. In the implementation process, a double-layer loop is used. The outer loop searches for all elements except the first element, and the inner loop searches the position to be inserted in the ordered list before the current element and moves it.

public class M04_Insert {
    public static void main(String[] args) {
        int[] arr = {10,40,90,20,80};
        insertSort(arr);
    }
    public static void insertSort (int[] arr) {
        int insertValue = 0;
        int insertIndex = 0;
        for (int i = 1; i < arr.length; i++) {
            // 待插入数的值和下标
            insertValue = arr[i];
            insertIndex = i - 1;
            // 写入位置
            while (insertIndex >= 0 && insertValue < arr[insertIndex]) {
                arr[insertIndex + 1] = arr[insertIndex];
                insertIndex--;
            }
            if (insertIndex + 1 != i) {
                arr[insertIndex + 1] = insertValue;
            }
            System.out.println("第" + i + "轮插入排序:"+Arrays.toString(arr));
        }
    }
}

Output result :

第1轮插入排序:[10, 40, 90, 20, 80]
第2轮插入排序:[10, 40, 90, 20, 80]
第3轮插入排序:[10, 20, 40, 90, 80]
第4轮插入排序:[10, 20, 40, 80, 90]

Three, search algorithm

The search algorithm refers to finding a specific information element in a group of elements. In computer applications, search is a common basic operation, such as the search of the symbol table in a compiler; the commonly used search algorithms are: sequential search, binary search, interpolation Find, Fibonacci Find.

1. Search in order

Sequential search is a basic search algorithm that traverses a set of elements according to the original sequence of the sequence and compares them with the elements to be searched one by one.

public class M05_OrderFind {
    public static void main(String[] args) {
        String[] arr = {"first","second","third"};
        System.out.println(seqSearch(arr,"second"));
    }
    public static int seqSearch(String[] arr, String value) {
        // 数组下标,-1代表没有
        int findIndex = -1 ;
        // 遍历并逐个对比
        for (int i = 0; i < arr.length; i++) {
            if(value.equals(arr[i])) {
                return i ;
            }
        }
        return findIndex ;
    }
}

2. Binary search

Binary search is also called Binary Search, which is an efficient search method. However, the binary search requires that the linear table must adopt a sequential storage structure, and the elements in the table are arranged in order by keywords.

public class M06_BinaryFind {
    public static void main(String[] args) {
        int arr[] = { 10, 20, 30, 40, 50 };
        int index = binarySearch (arr, 0, arr.length - 1, 40);
        System.out.println("index="+index);
    }
    public static int binarySearch(int[] arr, int leftIndex, int rightIndex, int findValue) {
        // leftIndex > rightIndex,没有查到
        if (leftIndex > rightIndex) {
            return -1;
        }
        int midIndex = (leftIndex + rightIndex) / 2;
        int midValue = arr[midIndex];
        // 向左递归
        if (findValue < midValue) {
            return binarySearch(arr, leftIndex, midIndex - 1, findValue);
        // 向右递归
        } else if (findValue > midValue) {
            return binarySearch(arr, midIndex + 1, rightIndex, findValue);
        // 直接找到
        } else {
            return midIndex;
        }
    }
}

If the elements to be queried are not ordered, you can sort them first and then search based on the sorting algorithm in the second module above.

Fourth, the source code address

GitHub·地址
https://github.com/cicadasmile/model-arithmetic-parent
GitEE·地址
https://gitee.com/cicadasmile/model-arithmetic-parent

Recommended reading: finishing programming system

Serial number project name GitHub address GitEE address Recommended
01 Java describes design patterns, algorithms, and data structures GitHub·click here GitEE·Click here ☆☆☆☆☆
02 Java foundation, concurrency, object-oriented, web development GitHub·click here GitEE·Click here ☆☆☆☆
03 Detailed explanation of SpringCloud microservice basic component case GitHub·click here GitEE·Click here ☆☆☆
04 Comprehensive case of SpringCloud microservice architecture GitHub·click here GitEE·Click here ☆☆☆☆☆
05 Getting started with SpringBoot framework basic application to advanced GitHub·click here GitEE·Click here ☆☆☆☆
06 SpringBoot framework integrates and develops common middleware GitHub·click here GitEE·Click here ☆☆☆☆☆
07 Basic case of data management, distribution, architecture design GitHub·click here GitEE·Click here ☆☆☆☆☆
08 Big data series, storage, components, computing and other frameworks GitHub·click here GitEE·Click here ☆☆☆☆☆

Guess you like

Origin blog.51cto.com/14439672/2536477