#include <stdio.h>
void bubbleSort(int A[], int n) {
int i, j, temp;
int flag;
for (i = 0; i < n - 1; i++) {
flag = 0; // assume already sorted
for (j = 0; j < n - 1 - i; j++) {
if (A[j] > A[j + 1]) {
// swap
temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
flag = 1; // swap happened
}
}
// no swaps → array already sorted
if (flag == 0)
break;
}
}
int main() {
int A[] = {5, 3, 4, 1, 2};
int n = sizeof(A) / sizeof(A[0]);
bubbleSort(A, n);
printf("Sorted array:\n");
for (int i = 0; i < n; i++)
printf("%d ", A[i]);
return 0;
}
I'm having trouble understanding the point of flag considering the code will already get the job done even eithout it and the number of steps increases with it as shown by visualizer.