Program : Check if 1-D array is sorted in ascending order in C++.
Solution :
#include <iostream> using namespace std; bool isSorted(int array[], int size) { for (int i = 1; i < size; i++) { if (array[i] < array[i - 1]) { return false; } } return true; } int main() { const int size = 5; int arr[size],i; cout << "Enter " << size << " elements of an array : "; for (i = 0; i < size; i++) { cin >> arr[i]; } bool sorted = isSorted(array, size); if (sorted) { cout << "The array is sorted in ascending order."; } else { cout << "The array is not sorted in ascending order."; } return 0; }
Output :
Enter 5 elements of an array: 10 12 33 34 38 The array is sorted in ascending order.
Dry Run :
Let’s walk through the code written inside the isSorted() function :
i | i<size | array[i]<array[i-1] | return false | i++ | return true |
1 | True | 10 < 12 (False) | ——- | 2 | |
2 | True | 12 < 33 (False) | ——- | 3 | |
3 | True | 33 < 34 (False) | ——- | 4 | |
4 | True | 34 < 38 (False) | ——- | 5 | |
5 | False | ——– | ——– | ——– | true |
So, from the above table, as per our given array, it will always return true because the input array is sorted in ascending order. After executing the for loop, it will return true to the main function and display “The array is sorted in ascending order”.
Want to practice more problems involving Array 1-D ? Click here.