Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Alaestor, discord: http://public.FutureGadgetLab.net
- Your task is to create an array sorting function.
- Given the following source, you must write the "sort" function.
- It should be simplistic and be your own function. Don't call an existing
- sorting function, and don't just copy+paste one from the web.
- */
- #include <iostream>
- #include <cstdio>
- #include <ctime>
- void sort(int* arr, const std::size_t size);
- void debugPrint(int* arr, const std::size_t size);
- bool isSorted(int* arr, const std::size_t size);
- int main()
- {
- srand(time(nullptr));
- constexpr const std::size_t max_index = 30;
- int array[max_index];
- for (std::size_t i = 0; i < max_index; ++i) array[i] = rand() - RAND_MAX/2;
- sort(array, max_index); // the function I want you to make
- //debugPrint(array, max_index);
- std::cout
- << "The array sort you made was a "
- << (isSorted(array, max_index) ? "Success." : "Failure!")
- << std::endl;
- }
- void sort(int* arr, const std::size_t size)
- { // you are only allowed to write code in this
- //////////////////////////////////////////////////////////////////////
- // bubblesort example
- // the following is a test and should be removed before giving to student
- int temp;
- std::size_t n = size;
- std::size_t newn;
- do
- {
- newn = 0;
- for (std::size_t i = 1; i < size; ++i)
- {
- if (arr[i-1] > arr[i])
- {
- temp = arr[i-1];
- arr[i-1] = arr[i];
- arr[i] = temp;
- newn = i;
- }
- }
- n = newn;
- }
- while (n != 0);
- //////////////////////////////////////////////////////////////////////
- }
- void debugPrint(int* arr, const std::size_t size)
- { // for debugging purposes
- for (std::size_t i = 0; i < size; ++i)
- std::cout << arr[i] << (i+1 != size ? ", " : "\n");
- std::cout << std::endl;
- }
- bool isSorted(int* arr, const std::size_t size)
- { // this is the code that tests if you've succeeded or failed
- for (std::size_t i = 0; i < size - 1; ++i)
- if (!(arr[i] <= arr[i+1])) return false;
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement