Advertisement
Guest User

Untitled

a guest
May 21st, 2015
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.06 KB | None | 0 0
  1. void bubble_sort(int values[], int size)
  2. {
  3.     // if no swaps were made we know the array is sorted
  4.     bool swaps_made;
  5.    
  6.     // help with swaping
  7.     int tmp;
  8.    
  9.     // don't make comparisons till the end of the array every time
  10.     // because going through the array once "bubbles" one element to the top
  11.     int compare_till = size - 1;
  12.    
  13.     do
  14.     {
  15.         swaps_made = false;
  16.         // loop for every elemtn up to the sorted portion
  17.         for (int i = 0; i < compare_till; i++)
  18.         {
  19.             // if the current element is bigger than the next one
  20.             if (values[i] > values[i + 1])
  21.             {
  22.                 // swap them
  23.                 tmp = values[i];
  24.                 values[i] = values[i + 1];
  25.                 values[i + 1] = tmp;
  26.                
  27.                 // be sure to go through the array again next time
  28.                 swaps_made = true;
  29.             }
  30.         }
  31.         // one element has "bubbled up", so make one less comparisons next time
  32.         compare_till--;
  33.     }  
  34.     while (swaps_made);
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement