Advertisement
ivanwidyan

Determine Is Array Sorted or Not, If Not, Sort It

Oct 24th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <ctime>
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. int findSmallestRemainingElement(int array[], int size, int index);
  7. void swap(int array[], int first_index, int second_index);
  8. bool sorted = true;
  9.  
  10. void sort(int array[], int size) {
  11.     for (int i = 0; i < size; i++) {
  12.         int index = findSmallestRemainingElement(array, size, i);
  13.         swap(array, i, index);
  14.     }
  15. }
  16.  
  17. int findSmallestRemainingElement(int array[], int size, int index) {
  18.     int index_of_smallest_value = index;
  19.     for (int i = index + 1; i < size; i++) {
  20.         if (array[i] < array[index_of_smallest_value]) {
  21.             index_of_smallest_value = i;
  22.             sorted = false;
  23.         }
  24.     }
  25.     return index_of_smallest_value;
  26. }
  27. void swap(int array[], int first_index, int second_index) {
  28.     int temp = array[first_index];
  29.     array[first_index] = array[second_index];
  30.     array[second_index] = temp;
  31. }
  32. // small helper method to display the before and after arrays
  33. void displayArray(int array[], int size) {
  34.     cout << "{";
  35.     for (int i = 0; i < size; i++) {
  36.         // you'll see this pattern a lot for nicely formatting
  37.         // lists--check if we're past the first element, and
  38.         // if so, append a comma
  39.         if (i != 0) {
  40.             cout << ", ";
  41.         }
  42.         cout << array[i];
  43.     }
  44.     cout << "}";
  45. }
  46.  
  47. int main() {
  48.     int arraySize;
  49.     cout << "Put The Size of The Array: ";
  50.     cin >> arraySize;
  51.     int *array = new int[arraySize];
  52.     srand(time(NULL));
  53.     for (int i = 0; i < arraySize; i++) {
  54.         // keep the numbers small so they're easy to read
  55.         array[i] = rand() % 100;
  56.     }
  57.     cout << "Original array: ";
  58.     displayArray(array, arraySize);
  59.     cout << '\n';
  60.     sort(array, arraySize);
  61.     if (sorted == false) {
  62.         cout << "Sorted array: ";
  63.         displayArray(array, arraySize);
  64.         cout << '\n';
  65.         return 0;
  66.     }
  67.     cout << "This array is sorted already" << endl;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement