Search code examples
c++arrayssortingbubble-sort

C++ Bubble Sorting


Hey i got this algorithm from my class called Bubble Sort. It uses two "for" one inside the other. But when i tried to do it with "while" it didnt work, aren't they equivalent ?

void bubbleSort(int v[], int n) {   // void workingBubble(int v[], int n){
  int fim = n - 1;                  //      int i, fim;
  int i = 0;                        //      for(fim=n-1; fim>0; fim--){
  int aux;                          //          for(i=0; i<fim; i++){
  while (fim > 0) {                 //              if(v[i] > v[i+1]){
      while (i < fim) {             //                  int temp = v[i];
          if (v[i] > v[i + 1]) {    //                  v[i] = v[i+1];
              aux = v[i];           //                  v[i+1] = temp;
              v[i] = v[i + 1];      //              }
              v[i + 1] = aux;       //          }
          }                         //      }
          i++;                      // }
      }                             //
      fim--;                        //
}}
                            

I commented the one that worked next to the other so i could compare, i thought it was the same but with while instead of for

Array = {10, 2, 8, 11, 5, 3, 27, 1}

Array after bubble sort = {2, 8, 10, 5, 3, 11, 1, 27}


Solution

  • Reset i to 0 each time before the inner loop:

    void bubbleSort(int v[], int n) {
      int fim = n - 1;
      int i;
      int aux;
      while (fim > 0) {
          i = 0;
          while (i < fim) {
              if (v[i] > v[i + 1]) {
                  aux = v[i];
                  v[i] = v[i + 1];
                  v[i + 1] = aux;
              }
              i++;
          }
          fim--;
      }
    }