Created
June 27, 2011 16:22
-
-
Save neesenk/1049209 to your computer and use it in GitHub Desktop.
交换数组的两部分
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stddef.h> | |
#define TYPE_SWAP(a,b) do { TYPE t = (a); (a) = (b); (b) = t; } while (0) | |
static inline void _reverse(TYPE *base, size_t n) | |
{ | |
size_t i = 0; | |
for (i = 0; i < n/2; i++) | |
TYPE_SWAP(base[i], base[n - i - 1]); | |
} | |
void reverse(TYPE *base, size_t n, size_t i) | |
{ | |
_reverse(base, i); | |
_reverse(base + i, n - i); | |
_reverse(base, n); | |
} | |
static inline void swap_array(TYPE *a, TYPE *b, size_t n) | |
{ | |
size_t i = 0; | |
for (i = 0; i < n; i++) | |
TYPE_SWAP(a[i], b[i]); | |
} | |
void reverse2(TYPE *base, size_t n, size_t i) | |
{ | |
while (n && i && i < n) { | |
size_t m = n - i > i ? i : n - i; | |
swap_array(base, base + n - m, m); | |
if (m < i) | |
base += m, i -= m; | |
n -= m; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment