# Bubble sort code

I tried avoiding nested loops and usage of too many variables. This is up for review and comments.

void bubble_Sort(int *arr, int n)
{
int i = 0;
int* temp = arr;

while(n > 1)
{
if(i == (n-1))
{
i=0;
n--;
temp = arr;
}

if(*temp > *(temp+1))
{
*temp ^= *(temp+1);
*(temp+1) ^= *temp;
*temp ^= *(temp+1);
}
temp++;
i++;
}
}

• My comment is argh, we have loops and nesting for a reason. Nov 20, 2016 at 18:51

This code is totally cryptic to me. Had you not named the function bubble_Sort or used it in the title of the question, I would have no clue what the code was supposed to do. Let alone trying to understand if it is implemented correctly.

You should document the purpose of the variables used, or at least give them less generic names than n, i, temp.

You could reduce some temporaries and other variables further with pointer arithmetic (which you're using in your XOR swap):

void bubble_sort(int *arr, int sz)
{
int n = 0;
while (n < sz-1) {
// array == end ?
if (arr == (arr+sz-n)) {
// set to beginning
arr = arr-n;
n = 0;
}
if (*arr > *(arr+1)) {
*arr ^= *(arr+1);
*(arr+1) ^= *arr;
*arr ^= *(arr+1);
// set to beginning and loop (no recursion)
arr = arr-n;
n = 0;
continue;
}
// prefer pre-increment to avoid temporary creation from post-increment
++n;
++arr;
}
}


It should be noted that while this avoids a lot of temporaries, the XOR swap algorithm might actually increase the time it takes to preform this operation (depending on bit width of the int).