[英]Bubble Sort so that all numbers ending in the digit 5 comes in ascending order
I am trying to implement a bubblesort of an array of integers so that all numbers ending in digit 5 comes first (ascending order), followed by all numbers which do not end in 5 (ascending order). 我正在尝试实现整数数组的冒泡排序,以便所有以数字5结尾的数字都首先出现(升序),然后是所有未以5结尾的数字(升序)。
Before BubbleSort: [5, 1, 23, 45, 65, 89, -85, -76] 在BubbleSort之前:[5、1、23、45、65、89,-85,-76]
After Bubblesort (ending digit 5 (ascending order)): [-85, 5, 45, 65, -76, 1, 23, 89] 在冒泡排序之后(尾数5(升序)):[-85、5、45、65,-76、1、23、89]
So I do know how to write the standard Bubblesort but I can't wrap my mind around the additional rule (ending in digit 5). 因此,我确实知道如何编写标准的Bubblesort,但是我无法将注意力集中在附加规则上(以数字5结尾)。 Any help is appreciated.
任何帮助表示赞赏。
Thanks 谢谢
The only thing that needs to change is the compare code. 唯一需要更改的是比较代码。
Assuming bubble sort code is working and uses a simple compare like: 假设冒泡排序代码正常工作,并使用简单的比较,例如:
if (a < b) ...
Create function as below. 创建功能如下。
a%10
will result in values -9,-8,...,8,9
. a%10
将产生值-9,-8,...,8,9
。 Test when this result is 5
or -5
. 测试此结果是
5
还是-5
。 The below tests when the |a%10| == 5
|a%10| == 5
时,下面的测试 |a%10| == 5
. |a%10| == 5
。
// Return 1 when a should come before b in the array.
int cmp5(int a, int b) {
int a5 = abs(a%10) == 5;
int b5 = abs(b%10) == 5;
// Since a and b are the same "five-ness", do a simple compare
if (a5 == b5) return a < b;
if (a5) return 1;
return 0;
// Could replace above 2 lines with `return a5;`
}
and call 并打电话
if (cmp5(a,b)) ...
As you said you know standard bubble sort, good now do the following 正如您所说,您知道标准气泡排序,现在请执行以下操作
one for multiples of 5 and other for remaining 一个为5的倍数,另一个为剩余
Now just make standard bubble sort function bubblesort(array[]) 现在只需制作标准的冒泡排序函数bubbleort(array [])
Filter the inputs to the two arrays 过滤两个数组的输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.