Bubble sort ascending failed to run

dickens_csl 注册会员
2023-02-25 21:09

Part of this answer references GPT, GPT_Pro to solve the problem better
This is because bubble sort is an algorithm for comparing data sizes, it compares two adjacent elements, Swap based on the size relationship. If you use "<" To compare, it means from smallest to largest, which is the ascending order; And if you use "> Order from largest to smallest, or descending. If bubble sort is used for descending order, it will fail because it will not sort the data properly.

As an example to illustrate: suppose you have an array [10, 5, 4, 9, 8], if you use ascending bubble sort(i.e., use "< Compare), then in the first cycle, 10 will be compared with 5, 5 will be compared with 4, 9 will be compared with 8; And it turns out that 5 is less than 10, 4 is less than 5, 8 is less than 9, and they switch places. The resulting array is [5, 4, 8, 9, 10], which is already an ordered ascending array.

While using descending bubble sort(i.e., using "> Compare), then in the first round, 10 will be compared with 5, 5 with 4, and 9 with 8. But since it's not true that 5 is greater than 10, 4 is greater than 5, and 8 is greater than 9, we're not going to swap them. The resulting array is [10, 5, 4, 9, 8], which is clearly still an unordered array.

So we can see that for bubble sort to work properly and sort data in ascending/descending order correctly, we need to select the correct size relation operator "<" based on what we are trying to achieve. "Or" > .
If the answer is helpful, please accept it.

duanhongqing 注册会员
2023-02-25 21:09


In your code, when j=9, arr[j+1] is arr[10], which is out of bounds
when it is changed to greater than, because j=9, if condition is met, resulting in data exchange, because arr[10] is out of bounds, resulting in illegal data write and crash