Pastebin launched a little side project called HostCabi.net, check it out ;-)Don't like ads? PRO users don't see any ads ;-)
Guest

rotate

By: a guest on Oct 12th, 2010  |  syntax: C  |  size: 0.92 KB  |  hits: 248  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <stdio.h>
  2. #include <assert.h>
  3. #include <math.h>
  4. #include <sys/types.h>
  5.  
  6. size_t fix_offset(ssize_t offset, size_t len) {
  7.     /* Behavior of modulus of negative is, I believe, not standardized by c89,
  8.        so I don't use it...
  9.     */
  10.     int neg = 0;
  11.     if (offset < 0)
  12.         neg = 1;
  13.     offset = abs(offset) % len;
  14.     if(neg) return len - offset;
  15.     return offset;
  16. }
  17.  
  18. void rotate(int *start, size_t len, ssize_t offset) {
  19.     if (len < 2) return;
  20.     offset = fix_offset(offset, len);
  21.     size_t res_len = len - offset;
  22.     int *scratch = start + res_len;
  23.     int ii = 0;
  24.     for (; ii < res_len; ++ii) {
  25.         int tmp = scratch[ii % offset];
  26.         scratch[ii % offset] = start[ii];
  27.         start[ii] = tmp;
  28.     }
  29.     size_t scratch_offset = offset - (ii % offset);
  30.     /*gcc -O3 does tail call optimization on this if you look at the asm...*/
  31.     rotate(scratch, offset, scratch_offset);
  32. }