Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. /*
  2. * Function: bubbleSort
  3. *
  4. * Recursively sorts an array of strings using the bubble sort algorithm
  5. *
  6. * Parameters:
  7. *  std::string strArray[]
  8. *  std::size_t size
  9. */
  10.  
  11. void bubbleSort(std::string strArray[], 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 (strArray[i] > strArray[i + 1])
  23.         {
  24.             swap(strArray[i], strArray[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(strArray, size - 1);
  34. }
  35.  
  36. /*
  37. * Function: swap
  38. *
  39. * Swaps the value stored at two string pointers
  40. *
  41. * Parameters:
  42. *  std::string* strPtrOne
  43. *  std::string* strPtrTwo
  44. */
  45.  
  46. void swap(std::string* strPtrOne, std::string* strPtrTwo)
  47. {
  48.     std::string temp;
  49.     *strPtrOne = temp;
  50.     *strPtrOne = *strPtrTwo;
  51.     *strPtrTwo = temp;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement