Advertisement
alaestor

FGL Homework: Sort Int Array

Feb 15th, 2018
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. /*
  2.     Alaestor, discord: http://public.FutureGadgetLab.net
  3.  
  4.     Your task is to create an array sorting function.
  5.  
  6.     Given the following source, you must write the "sort" function.
  7.     It should be simplistic and be your own function. Don't call an existing
  8.     sorting function, and don't just copy+paste one from the web.
  9. */
  10. #include <iostream>
  11. #include <cstdio>
  12. #include <ctime>
  13.  
  14. void sort(int* arr, const std::size_t size);
  15. void debugPrint(int* arr, const std::size_t size);
  16. bool isSorted(int* arr, const std::size_t size);
  17.  
  18. int main()
  19. {
  20.     srand(time(nullptr));
  21.  
  22.     constexpr const std::size_t max_index = 30;
  23.     int array[max_index];
  24.     for (std::size_t i = 0; i < max_index; ++i) array[i] = rand() - RAND_MAX/2;
  25.  
  26.     sort(array, max_index); // the function I want you to make
  27.     //debugPrint(array, max_index);
  28.  
  29.     std::cout
  30.         << "The array sort you made was a "
  31.         << (isSorted(array, max_index) ? "Success." : "Failure!")
  32.         << std::endl;
  33. }
  34.  
  35. void sort(int* arr, const std::size_t size)
  36. { // you are only allowed to write code in this
  37.  
  38. //////////////////////////////////////////////////////////////////////
  39.     // bubblesort example
  40.     // the following is a test and should be removed before giving to student
  41.     int temp;
  42.     std::size_t n = size;
  43.     std::size_t newn;
  44.     do
  45.     {
  46.         newn = 0;
  47.         for (std::size_t i = 1; i < size; ++i)
  48.         {
  49.             if (arr[i-1] > arr[i])
  50.             {
  51.                 temp = arr[i-1];
  52.                 arr[i-1] = arr[i];
  53.                 arr[i] = temp;
  54.                 newn = i;
  55.             }
  56.         }
  57.         n = newn;
  58.     }
  59.     while (n != 0);
  60. //////////////////////////////////////////////////////////////////////
  61. }
  62.  
  63. void debugPrint(int* arr, const std::size_t size)
  64. { // for debugging purposes
  65.     for (std::size_t i = 0; i < size; ++i)
  66.         std::cout << arr[i] << (i+1 != size ? ", " : "\n");
  67.  
  68.     std::cout << std::endl;
  69. }
  70.  
  71. bool isSorted(int* arr, const std::size_t size)
  72. { // this is the code that tests if you've succeeded or failed
  73.     for (std::size_t i = 0; i < size - 1; ++i)
  74.         if (!(arr[i] <= arr[i+1])) return false;
  75.  
  76.     return true;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement