Introduction to Greedy Algorithm

Today is the first lesson of the 11th week of the course.

Some students showed great interest in sorting algorithms, and others said that the principles of object-oriented programming were too dry to understand. Today's course I will change the subject and talk about something interesting.

This is the first time that our little secret circle "Attack Java Newcomer" course involves knowledge of algorithm design. Algorithm design is a relatively interesting topic. We will talk about a lot of knowledge and data structure related to searching and sorting later. If you can learn algorithm design first, you will have a deeper understanding.

What is an algorithm

Algorithm, algorithm, this thing is just a way to solve the problem. Nothing advanced. For example, a story about Gauss that everyone is familiar with is that when Gauss was in elementary school, the teacher asked him to calculate the sum from 1 to 100. Other students did it manually. Only Gauss used the arithmetic sequence of sum formulas. Get the answer quickly. Two ways of solving the problem, these are two algorithms. We have introduced the problem of time complexity before. Obviously, calculating 99 additions and getting the result, the time complexity of this algorithm is O(n), and the time complexity of directly using the formula to get the result of one multiplication is O(1 ). This is an example of an algorithm.

Here is another joke. A young girl borrowed a large stack of books from the library and went out with a hug. The alarm went off. The young girl was preparing a local copy to see which one had not been degaussed. The administrator exclaimed: "This When will I have to try?" Then the aunt divided the book in half, went to try and it didn't sound, and then divided the remaining half of the book in half. Aunt's solution is called divide and conquer. This is also an example of algorithm design. The time complexity of the little girl's solution is O(n), and the time complexity of the aunt's solution is O(log n). Of course, someone replied early in the paragraph: If more than one book is not degaussed, the aunt's solution will be dead. It can be seen that designing a correct algorithm is not an easy task.

greedy

The topic we are introducing today is greedy algorithms. This is a relatively easy algorithm. I dare not give a strict definition here, because it took me three years to understand the ineffectiveness of greed and dynamic programming. It took a thousand days from the first time I heard that there was no aftereffect to the one day I realized it. Therefore, I will not talk about the definition here, let's just look at the example.

Greedy algorithm, if you don't need to manually prove the mathematical nature of a problem, it is actually relatively simple. Consider this example: Suppose there is a backpack with a maximum capacity of 50KG. Now there are various liquids of different values. For example, if there is water, its value is 10 per kilogram, for a total of 100KG; alcohol, its value is 20 per kilogram, A total of 30KG; with oil, the value is 25 per kilogram, a total of 30KG. Ask what kind of solution can maximize the total value of the liquid in the backpack? Obviously, this is a problem for elementary school students, choosing expensive pretends. Who will not. That is to install 30KG oil first, because oil is the most expensive, and the remaining 20KG capacity is filled with alcohol, because alcohol is more expensive than water.

Okay, then, this thinking process is greedy: every stage of decision-making is to find the optimal solution under current conditions. Of course, for this problem, the correctness of this solution is obvious. The most difficult part of greedy problems is that the correctness cannot be proved. We don't care about this. After all, we are not doing algorithm research, as long as we can use greed to solve specific programming problems.

Let's look at a simple example. Find change in the store. For example, if the salesperson wants to give you 37 yuan, what kind of plan is the one with the least amount of money? It must be that the larger the face value of the recovered change, the smaller the final number of sheets. So we can use greedy methods to solve this problem. First look for a 20. If you find another 20, it will exceed 37. This is not good, so I will find another 10 yuan, then 5 yuan and two. The final solution is obtained, which is also a typical greedy computing solution.

Sort

Under the guidance of greedy thinking, a sorting algorithm is also designed, which is called selective sorting. The idea of ​​sorting is simple. Since my goal is to rank a bunch of numbers from small to large, isn't it good for me to solve this problem in stages? The first step is to find the smallest number and place it in the first place. In the second step, find the smallest number among all the remaining numbers and place it in the second place, and so on.

public class ChooseSort implements  Sorter {
    public void sort(int[] arr) {
        int pivot, pos = -1;

        for (int i = 0; i < arr.length; i++) {
            pivot = Integer.MAX_VALUE;
            for (int j = i; j < arr.length; j++) {
                if (pivot > arr[j]) {
                    pivot = arr[j];
                    pos = j;
                }
            }
            arr[pos] = arr[i];
            arr[i] = pivot;
        }
    }
}

We start from the first iteration, when i is 0, the inner loop is to find the minimum value in the array from 0 to the end of the array. Then swap this minimum value with the i-th bit, here is the 0th bit. In this way, we put the first smallest number in the 0th position of the array.

In the second iteration, the smallest number from the first to the end of the array is placed in the first position of the array.

This process continues until n iterations are completed. Obviously, the time complexity of selection sort is O(n^2).

See, from the point of view of algorithm design, do you feel that the sorting problem has a rule to follow at once.

operation:

1. There is an ordered array with length n, shuffle it, but the distance between each number from the original position will not exceed m, where m is much smaller than n. Excuse me, can you design a method to make the array re-ordered, and the time complexity is O(mn)?

2. Learn about PriorityQueue, and try to use this data structure to rewrite the selection sort?

Idea: In the case of PriorityQueue, it is convenient to put all the arrays in minHeap, and if they are sorted from small to large, they will pop out from the beginning to sort them. For MaxHeap, over ride comparator and pop backward.

 

Transfer from: https://zhuanlan.zhihu.com/p/25769975

Guess you like

Origin blog.csdn.net/daobuxinzi/article/details/109404300