create a bool flag before the loop starts and set it to false. when a swap is made change the flag to true. on next loop iteration if the flag is still false then no swaps were performed during the previous loop iteration.
and please next time use code tags.
Ancient Dragon
Retired & Loving It
30,046 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,342
You cant as such check for such conditions in case of a simple sort like bubble sort.
Take for eg. this array.
1 2 3 4 5 6 8 7
During the first seven passes no swap is performed since the next number is always greater than the current but a final swap is done in the last pass to sort the array. You cant as such terminate a bubble sort based on the flag that swap is performed or not.
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 733
You cant as such check for such conditions in case of a simple sort like bubble sort.
Take for eg. this array.
1 2 3 4 5 6 8 7
During the first seven passes no swap is performed since the next number is always greater than the current but a final swap is done in the last pass to sort the array. You cant as such terminate a bubble sort based on the flag that swap is performed or not.
Yes you can. You set the swap flag to FALSE between the two loops (inside the outer loop, before the inner loop). When the inner loop exits and a swap has been made, the swap flag should be TRUE. If no swap has been made, the flag should be FALSE and it's safe to exit.
WaltP
Posting Sage w/ dash of thyme
10,492 posts since May 2006
Reputation Points: 3,348
Solved Threads: 943