I was just practicing and thought about writing a code for bubble sort. can anyone tell me why this code is not giving me the desired output and what could be the possible solution to it?

bool swap = true;
int temp;
for(int count = 0; swap == false; count++)
    swap = false;
    for (int i = 0, j = i + 1; j < length; i++) {
        if(data[i] > data[j]) {
            temp = data[i];
            data[i] = data[j];
            data[j] = temp;
            swap = true; 

The condition for your for loop to begin running is that swab != true. However, when you initialized swab at the beginning of the value, you set its value to true. Under those conditions, the loop will never begin.

  • Solved that problem but now the list is been printed in a unsorted manner exactly the same as it was entered May 20 '16 at 6:37
  • Is this the corrected code above? Because you still have the same problem that the code will not run. You have swab = true then your condition in the loop is saying while swab == false, run this code, but it won't run because swab is true.
    – Claire
    May 20 '16 at 7:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .