c++bubble-sort

BubbleSort implemented with do-while loop


I am learning basic sorting algorithms. I wrote below but no sure why it never completely sorts it? I thought it would only meet the exit criteria (flag not set to 1) if it iterates over the entire array with no sorting needed.

void bubbleSort(int lst[], int size)
{
    int flag; 
    do{
    for(int i = 0; i < size-1; i++) 
    {
        flag = 0; //nothing sorted yet 
        int temp = lst[i];
        if(lst[i] > lst[i + 1])
        {
            //swap values  
            int temp = lst[i]; 
            lst[i] = lst[i + 1];
            lst[i+1] = temp; 
            flag = 1; //sort happened set flag 
        }

    }
    }while (flag != 0); 
}

Solution

  • You were almost there. All you need to do is move where you initialize the flag:

    void bubbleSort(int lst[], int size) {
        int flag;
        do {
            flag = 0; //nothing sorted yet
            for(int i = 0; i < size-1; i++) {
                int temp = lst[i];
                if(lst[i] > lst[i + 1]) {
                    //swap values
                    int temp = lst[i];
                    lst[i] = lst[i + 1];
                    lst[i+1] = temp;
                    flag = 1; //sort happened set flag
                }
            }
        } while (flag != 0);
    }
    

    If you set flag to 0 within the for loop, then any time you set flag within the if, the flag will get reset on the next iteration of the for loop.