I'm trying to check if a vector is sorted or not with a for loop but it's not working properly
until I make a small change but the logic seem to be the same to me.
this is the code:
vector <int> is_list_sorted(vector <int> list_of_numbers){
bool list_is_sorted = true;
for(int i = 0; i < list_of_numbers.size(); i ){
if(list_of_number[i] > list_of_numbers[i 1]){
list_is_sorted = false;
}
}
return list_is_sorted;
}
int main(){
if(list_is_sorted(vector1){
cout << "the list is sorted" << endl;
}
else{
cout << "the list is not sorted << endl;
}
return 0;
}
I tested this function on three different vectors and the output is always the same "the list is
not sorted" until I make a small change in the actual function and instead of:
for(int i = 0; i < list_of_numbers.size(); i ){
if(list_of_number[i] > list_of_numbers[i 1]){
list_is_sorted = false;
}
}
I make it:
for(int i = 1; i < list_of_numbers.size(); i ){
if(list_of_number[i] < list_of_numbers[i - 1]){
list_is_sorted = false;
}
}
what's the bug?
CodePudding user response:
With the loop
for(int i = 0; i < list_of_numbers.size(); i )
then list_of_numbers[i 1]
will be out of bounds for the last element.
If you go out of bounds you will have undefined behavior.
A different solution would be to change the loop to:
for(int i = 0; i < list_of_numbers.size() - 1; i )
Then i 1
will not be an out of bounds index anymore.
On another note: As soon as you notice that the vector isn't sorted you can return false
immediately. You don't need to check the remainder of the vector.