I am confused about one line code of my c++ homework, and please explain to me. My question is what does this line of code meaning? "while ( !sorted )". I am really confused about this. I know !sorted refers to not sorted. So this line means while not sorted, sorted is true and for the following condition? Please explain this to me, I'm really really really confused! Moreover, why does professor write sorted = false at the last line? Thank you! This is the question and the answer. The function shown below will sort an integer array in ascending (increasing) order. That is, after calling sort the smallest element will be at index 0, the next smallest at index 1, etc. What would you need to change to sort the array in descending (decreasing) order? Discussion: All you need to do is change the comparison in the if statement that checks if adjacent elements are out of order. Change it from ">" to "<". See change below. void sort( int list[], int length ) { int index, temp; bool sorted = false; while ( !sorted ) { sorted = true for ( index = 0; index < length - 1; index++ ) if ( list[index] < list[index+1] ) { temp = list[index]; list[index] = list[index+1]; list[index+1] = temp; sorted = false; } } }
I am confused about one line code of my c++ homework, and please explain to me.
My question is what does this line of code meaning? "while ( !sorted )". I am really confused about this. I know !sorted refers to not sorted. So this line means while not sorted, sorted is true and for the following condition? Please explain this to me, I'm really really really confused!
Moreover, why does professor write sorted = false at the last line? Thank you!
This is the question and the answer. The function shown below will sort an integer array in ascending (increasing) order. That is, after calling sort the smallest element will be at index 0, the next smallest at index 1, etc. What would you need to change to sort the array in descending (decreasing) order?
Discussion: All you need to do is change the comparison in the if statement that checks if adjacent elements are out of order. Change it from ">" to "<". See change below.
void sort( int list[], int length ) { int index, temp; bool sorted = false; while ( !sorted ) { sorted = true for ( index = 0; index < length - 1; index++ ) if ( list[index] < list[index+1] ) { temp = list[index]; list[index] = list[index+1]; list[index+1] = temp; sorted = false; } } }
Trending now
This is a popular solution!
Step by step
Solved in 5 steps with 2 images