Pratik Devikar
PRO
2 months ago
Pratikcountry asked

Why do we use i < arr.size() - 1 in the outer loop of Bubble Sort? I didn’t understand what it means to “decrease the iteration by 1.”

Abhay Jajodia
Expert
last month
Abhay Jajodia answered

Hi Pratik,

Great question — this part can be a little tricky at first.

In Bubble Sort, we compare and swap adjacent elements to move the largest value to the end of the array in each pass. That’s why we don’t need the outer loop to run through the entire array.

Let’s say the array has n elements. After the first full pass, the largest element is already in its correct place at the end. So in the next pass, we only need to go up to n - 2. That’s why the outer loop runs only n - 1 times — like this:

for (int i = 0; i < arr.size() - 1; ++i)

After each pass, one more element is sorted and doesn’t need to be touched again. So we reduce the number of iterations in the outer loop by 1 compared to the total size of the array.

This helps avoid unnecessary comparisons and makes the algorithm more efficient.

If you have more questions, I’m here to help.

C++
This question was asked as part of the DSA with C++ course.