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).
Before BubbleSort: [5, 1, 23, 45, 65, 89, -85, -76]
After Bubblesort (ending digit 5 (ascending order)): [-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). 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
. Test when this result is 5
or -5
. The below tests when the |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
Now just make standard bubble sort function bubblesort(array[])
Filter the inputs to the two arrays
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.