Good day. So life has developed so that from recent time I became a proud student of one of the best universities of my country. Good or bad is a moot point, but it is not the point. The funny thing is that in the laboratory the teacher is either for entertainment, or to remind me once again that I am quite foul about algorithms, from time to time he gives out tasks different from what the rest of the group gets. One of the last, which, as for me, worthy of your attention is the sorting of the array without using conditional operators (if, switch, and the like).
Since I had previously lived in the warm world of frameworks and libraries, and I had never had such tasks before me, I was slightly surprised at such a lab. In general, despite the teacher’s numeral attempts to push me to the correct solution with phrases like “the numbers are limited to the range from 0 to 100” and “more than one array can be used”, it was not possible to find solutions, at least for the period of the pair. In general, the pair ended with the fact that 5 minutes before its completion of the task about sorting was replaced by some trifle, like counting the number of different digits in the number.
And as sometimes happens, instead of happily forgetting about this labarator and continuing to enjoy life, I occasionally returned to the task of sorting, and yet came up with its solution. Actually, and I want to share with you. It came out surprisingly simple and without the use of additional arrays (so most likely the problem has another solution, probably).
That's actually the program code:
#include <iostream> using namespace std; int myAbs(int a){ int oldByte = (a >> 31)& 0x1; return -a*(1+oldByte-1)-a*(oldByte-1); } int getMax(int a, int b) { return (a + b + myAbs(a - b)) / 2; } int getMin(int a, int b) { return (a + b - myAbs(a - b)) / 2; } int main() { int arr[] = {34, 12, 24, 65, 63, 22}; int arraySize = (sizeof(arr) / sizeof(*arr)); int maxPosition = 0; int maxElement = arr[0]; int minValue= arr[0]; for (int k = 0; k < arraySize; k++) { for (int i = k; i < arraySize; i++) { int newMax = getMax(maxElement, arr[i]); minValue = getMin(minValue, arr[i]); maxPosition =getMin((myAbs(newMax ^ maxElement) + 1) * (maxPosition + 1), (myAbs(newMax ^ arr[i]) + 1) * (i + 1)) -1; maxElement = newMax; } int buf = arr[k]; arr[k] = maxElement; arr[maxPosition] = buf; maxElement = minValue; } for(int a:arr){ cout<<a<<endl; } return 0; }
PS In the university is even interesting.