Search code examples
csortingbubble-sort

What did I miss? Issue with bubble sort method


I want to use a bubble sort method for my homework and it doesn't work, I can't find the mistake

 void bubbleSort(int arr[], int n) 
   { 
     int i,j; 
     for (i = 0; i < n-1; i++)       
      // last i elements are already in place    
     for (j = 0; j < n-i; j++) 
       if (arr[j] > arr[j+1]) 
         swap(&arr[j], &arr[j+1]); 
  }

Can someone help me? Thanks in advance


Solution

  • Notice the second loop stop condition should be n - i - 1

    void bubbleSort(int arr[], int n) 
    { 
        int i, j; 
        for (i = 0; i < n - 1; i++)    
            // Last i elements are already in place    
            for (j = 0; j < n - i - 1; j++)  // **Added n - i - 1**
                if (arr[j] > arr[j+1]) 
                    swap(&arr[j], &arr[j+1]); 
    }
    

    more on bubble sort here: Link