课程: Java Algorithms

Optimize an algorithm in Java - Java教程

课程: Java Algorithms

Optimize an algorithm in Java

- [Instructor] While studying algorithmic theory is important, it's vital to apply theory to practice. Let's modify a Java algorithm and make it more efficient. I've opened up this sample code in IntelliJ, a Java IDE, but feel free to use the IDE of your choice. You can find the sample code in the exercise files of this course. In this file, we have an algorithm called Find Maximum. It finds the largest of three numbers. If there are duplicate entries, we still return whatever the maximum is. Now inside this algorithm, we do several comparisons in order to find the maximum of the three numbers. We can actually eliminate some of these comparisons and make our algorithm more efficient by using assumptions. Now inside this algorithm, we do several comparisons to find the maximum of the three numbers. We can actually eliminate some of these comparisons and make our algorithm more efficient by using assumptions. Instead of doing multiple checks with each input, we can keep track of the maximum so far using a variable. Let's create a new function with our refactor. We'll call it findMaximum2. Inside the function, we'll create a variable called max and start it off at a. Then we'll compare the max to b. If b is greater than the max, then we'll set the max equal to b. Before, we had to add checks for if a and c were equal. With this implementation, it doesn't matter whether they're equal because the value is already stored in the max. At this point, the max variable contains the maximum of a and b. To check whether c is greater, we just need one more comparison. If c is greater than the max, then we'll set the max equal to c. Now the max variable contains the maximum of a, b and c. This is exactly what we're looking for so we'll return it from the function. Let's use the new algorithms implementation. To run it, I'll click the Play button. In the output, we get the maximum of each set of values. The new implementation only does two comparisons per call. The code is also more readable with the defined variable and less comparisons. We use the assumption that the max variable will contain the maximum for each point in the program's execution. When we check the max with c, we assume the max variable holds the maximum of a and b. This allows us to do less comparisons and optimize the algorithm.

内容