Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. /*
  2. * Function: bubbleSort
  3. *
  4. * Recursively sorts an array of numbers using the bubble sort algorithm
  5. *
  6. * Parameters:
  7. *  long long array[]
  8. *  std::size_t size
  9. */
  10.  
  11. void bubbleSort(long long array[], std::size_t size)
  12. {
  13.     // base case
  14.     if (size == 1)
  15.         return;
  16.  
  17.     // to check if swap was made after each pass
  18.     bool swapMade{ false };
  19.  
  20.     for (std::size_t i{ 0 }; i < size - 1; i++)
  21.     {
  22.         if (array[i] > array[i + 1])
  23.         {
  24.             swap(array[i], array[i + 1]);
  25.             swapMade = true;
  26.         }
  27.     }
  28.  
  29.     // if no swap was made, array is sorted
  30.     if (!swapMade)
  31.         return;
  32.  
  33.     bubbleSort(array, size - 1);
  34. }
  35.  
  36. /*
  37. * Function: swap
  38. *
  39. * Swaps the value stored at two pointers
  40. *
  41. * Parameters:
  42. *  long long* ptrOne
  43. *  long long* ptrTwo
  44. */
  45.  
  46. void swap(long long* ptrOne, long long* ptrTwo)
  47. {
  48.     long long temp;
  49.     *ptrOne = temp;
  50.     *ptrOne = *ptrTwo;
  51.     *ptrTwo = temp;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement