G
G
Goddamnboy2019-05-11 14:37:26
C++ / C#
Goddamnboy, 2019-05-11 14:37:26

What is the second loop in the algorithm for?

Here is bubble sort in C++. What is the second "for" loop (with variable j) in it for?

for (int i = 0; i < size - 1; i++) {
    for (int j = 0; j < size - i - 1; j++) {   //<- для чего он??
      if (arr[j] > arr[j + 1]) {
        temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Developer, 2019-05-11
@samodum

The second loop is needed so that the complexity of the algorithm is O(n^2)
:)

D
Dimonchik, 2019-05-11
@dimonchik2013

to be bored first

B
bkosun, 2019-05-11
@bkosun

The algorithm consists of repeated passes through the sorted array. For each pass, the elements are sequentially compared in pairs and, if the order in the pair is incorrect, the elements are exchanged. Passes through the array are repeated N-1 times or until at the next pass it turns out that the exchanges are no longer needed, which means that the array is sorted. With each passage of the algorithm through the inner loop, the next largest element of the array is put in its place at the end of the array next to the previous “largest element”, and the smallest element moves one position to the beginning of the array (“floats” to the desired position, like a bubble in water - hence the name of the algorithm).

https://ru.wikipedia.org/wiki/%D0%A1%D0%BE%D1%80%D...

A
Alexander Skusnov, 2019-05-11
@AlexSku

The inner cycle is the rise of one bubble. Outer - raise all the bubbles.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question