Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

A little help please

Name: Anonymous 2007-09-05 15:29 ID:so4w/yz5

void reverseHalves(int a[], int size)
{
    int i, t;

      if((size%2) != 0)  Size ODD
      {
        for(i=0;i<=((size/2)-1);i++)
        {
            t = a[i];
            a[i] = a[(size/2)+i+1];
            a[(size/2)+i+1] = t;
        }
      }

      if((size%2) == 0)  Size EVEN
      {
        for(i=0;i<=((size/2)-1);i++)
         {
              t = a[i];
              a[i] = a[(size/2)+i];
              a[(size/2)+i] = t;
          }
      }

    return;
}


This function swaps the halves of an array.

e.g.

1
2
3
4

comes out as:

3
4
1
2

I handed it in to my professor and he said he wants me to do it over using only one loop. The reason I used two loops in the first place because the program would crash when based on whether or not an odd/even amount of elements were present for the array. He said I could used a nested for loop, but I haven't been able to figure out how to create it.

Name: Anonymous 2007-09-05 22:59 ID:Heaven

>>20
int t[size/2];
that's not valid C/C++. you can't statically allocate a variable amount - you have to throw that shit on the heap, unfortunately.

void swap_halves( int *a, unsigned int s ) {
    for ( int i = 0; i < ( ( s >> 1 ) + ( s & 1 ) ); ++i ) {
        a[i] ^= a[ i + ( s >> 1 ) + ( s & 1 ) ];
        a[ i + ( s >> 1 ) + ( s & 1 ) ] ^= a[i];
        a[i] ^= a[ i + ( s >> 1 ) + ( s & 1 ) ];
    }
}

tee hee.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List