Repeatedly swap adjacent elements if they are in wrong order → Largest element “bubbles” to the end each pass
void bubbleSort(int arr[], int n)
{
for(int i=n-1;i>0;i--){
bool swapped = false;
for(int j=0;j<i;j++){
if(arr[j]>arr[j+1]){
swap(arr[j],arr[j+1]);
swapped = true;
}
}
if(!swapped) break;
}
}
If no swaps in a pass → array already sorted → break early
👉 This is what theswapped flag does
Pick the smallest element from unsorted part → place it at correct position (i)