
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.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer
