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 some sequence of actions that must be performed to achieve the desired result . We often use algorithms in our daily lives. For example, every morning you have a task: to come to school or work, and at the same time be:
- Dressed
- clean
- full
- Wake up with an alarm.
- Take a shower, wash.
- 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 each name from our list in this dictionary.
- Write down on a piece of paper on which page of the dictionary the name is located.
- Put the names in order using notes on a piece of paper.
for
that does 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 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 execute N outputs to the console. Let's consider 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
in which we insert some numbers. We need to evaluate the complexity of the algorithm for inserting a single number in LinkedList
our example, and how it depends on the number of elements in the list. The answer is O(1) - constant complexity . Why? Note that each time we insert a number at the beginning of the list. In addition, as you remember, when you insert numbers into LinkedList
elements, they don’t move 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 number х
, and we insert the number y at the beginning of the list, all it takes is:
x.previous = y;
y.previous = null;
y.next = x;
For this redefinition of references , it doesn’t matter to us how many numbers are currently inLinkedList
- at least one, at least a billion. The complexity of the algorithm will be constant - O(1).
GO TO FULL VERSION