The basic idea in bubble sort is to compare two successor elements and interchange them if they are not in proper order. After each pass the largest unsorted element is placed at its correct position.
If there are “n” elements then
After the first pass the largest element is placed at (n-1) th position. After the second pass the 2nd largest element is placed at n-2 th position and so on.
All the elements will be sorted after a maximum of n-1 passes.
But it is possible that the elements may get sorted before n-1 passes. So there should be a way to detect that the array is sorted or not. And for the same we use a variable swapped.