3
\$\begingroup\$

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++; 
 } 
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 20, 2016 at 18:11
\$\endgroup\$
1
  • 1
    \$\begingroup\$ My comment is argh, we have loops and nesting for a reason. \$\endgroup\$ Commented Nov 20, 2016 at 18:51

2 Answers 2

2
\$\begingroup\$

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.

answered Nov 20, 2016 at 23:24
\$\endgroup\$
1
\$\begingroup\$

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).

answered Nov 20, 2016 at 22:19
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.