Hello! Today's lecture will be a little different from the rest. It will differ in that it is only indirectly related to Java. However, this topic is very important for every programmer. We'll talk about algorithms . What is an algorithm? In simple terms, this is a certain sequence of actions that must be performed to achieve the desired result . We often use algorithms in everyday life. For example, every morning you are faced with a task: to come to school or work, and at the same time be:
- Dressed
- Clean
- Well-fed
- Wake up to an alarm clock.
- Take a shower, wash your face.
- Prepare breakfast, make coffee/tea.
- Eat.
- If you haven’t ironed your clothes since the evening, iron them.
- Get dressed.
- Leave the house.
- Buy or download on the Internet “Dictionary of Russian Personal Names” 1966 edition.
- Find every name on our list in this dictionary.
- Write down on a piece of paper which page of the dictionary the name is on.
- Put the names in order using the notes on a piece of paper.
for
that performs this task
int[] numbers = new int[100];
// ..заполняем массив числами
for (int i: numbers) {
System.out.println(i);
}
What is the complexity of the written algorithm? Linear, O(N). The number of actions that the program must perform depends on exactly how many numbers were passed into it. If there are 100 numbers in the array, there will be 100 actions (outputs on the screen). If there are 10,000 numbers in the array, 10,000 actions will need to be performed. Can our algorithm be improved? No. In any case, we will have to make N passes through the array and perform N outputs to the console. Let's look at another example.
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(0, 20202);
numbers.add(0, 123);
numbers.add(0, 8283);
}
We have an empty one LinkedList
into which we insert several numbers. We need to estimate the complexity of the algorithm for inserting a single number into LinkedList
our example, and how it depends on the number of elements in the list. The answer is O(1) - constant complexity . Why? Please note: each time we insert a number at the beginning of the list. In addition, as you remember, when inserting numbers into LinkedList
elements, they are not shifted anywhere - links are redefined (if you suddenly forgot how LinkedList works, take a look at one of our old lectures ). If now the first number in our list is the number х
, and we insert the number y at the beginning of the list, all that is needed is:
x.previous = y;
y.previous = null;
y.next = x;
For this reference redefinition, it doesn’t matter to us how many numbers there are nowLinkedList
- at least one, at least a billion. The complexity of the algorithm will be constant - O(1).
GO TO FULL VERSION