#help with understanding optimized bubble sort

1 messages · Page 1 of 1 (latest)

summer hill
#

#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.

grim widgetBOT
#

When your question is answered use !solved or the button below to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

foggy thicket
#

have you checked it with a sorted array and partially sorted array?

summer hill