Answer the question
In order to leave comments, you need to log in
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
The second loop is needed so that the complexity of the algorithm is O(n^2)
:)
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).
The inner cycle is the rise of one bubble. Outer - raise all the bubbles.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question