My assignment is to " write the following function that returns true if the list is already sorted in increasing order:
bool isSorted(constint [list], size)
" Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. Here is a sample run. Note that the first number in the input indicates the number of elements in the list. This number is not part of the list. Assume the maximum list size is 80.
1 2
Enter list: 8 10 1 5 16 61 9 11 1
The List is not sorted
1 2
Enter List: 10 1 1 3 4 4 5 7 9 11 21
The list is already sorted
I am having trouble with this, I do not know what to put in the body of the bool function to determine weather or not it should return true or false. My first thought was to put if statements such as if index[1] < [2] && [2] < [3] and so forth until it made it to the max of 80 integers than have it evaluate to true if all of those were right but there has to be another way. I am also a little lost on how to pass the array to the function. This is what I have so far.
#include <iostream>
usingnamespace std;
//create a function that determines if the list is sorted or not;
bool issorted(constint list[], int size)
{
returntrue;
}
int main()
{
//Allow user input
constint size = 80;
int issorted[size];
cout << " Please enter list " << " " ;
for (int i = 0; i < 80; i++)
cin >> issorted[i];
//call upon the issorted function
for (int k = 0; k < 99; k++)
cout << issorted[k], 99;
system ("pause");
return 0;
}
If someone could at least point me in the right direction I would be very grateful.
If a list is already sorted in increasing order, that means the nth element will always be smaller than the n+1th element.
So you'll need to make a for-loop that iterates through the array up to size-1.
With each pass, check if arr[n]>arr[n+1]. As you can guess, you will do this using an if-statement. Now if the list is already sorted in increasing order, you should never enter this if-statement. Meaning, if the if-statement is in fact entered, you can return a false right then and there, as you know that the list is not sorted and there is no need to check the rest of the array.
All this is within the for-loop. You can safely assume that if you've exited the for-loop your list is sorted, thus you can return a true outside the for-loop.
//assuming that the array is sorted in increasing order
#include<iostream>
usingnamespace std;
bool isSorted(int arr[], int size){
//taking input
for(int i=0; i<size; i++)
cin>>arr[i];
//checking if n+1th element is greater then the nth order
for(int a=0; a<(size-1); a++){
if(arr[a]<=arr[a+1])
continue;
elsereturnfalse;
}
returntrue;
}
int main(){
int arr[10];
constunsignedint size=10;
cout<<"input you array(size<=10)\n";
bool result=isSorted(arr,size);
if(result)
cout<<"array is sorted\n";
else
cout<<"array is not sorted\n";
return 0;
}