Skip to content

Instantly share code, notes, and snippets.

@jimexist
Created March 30, 2014 02:14
Show Gist options
  • Save jimexist/9866323 to your computer and use it in GitHub Desktop.
Save jimexist/9866323 to your computer and use it in GitHub Desktop.
interleave two halves of an array
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
static void swap(int* data, int c) {
for (int i=0; c > 0; i+=2, --c) {
int tmp = data[i];
data[i] = data[i+1];
data[i+1] = tmp;
}
}
static void interleave(int* data, int size) {
if (size % 2 == 1) {
size--;
}
int half = size / 2;
int j = 1;
for (int i=half-1; i>0; --i) {
swap(data+i, j++);
}
}
int main(int argc, char** argv) {
int size = argc-1;
int* data = (int*) malloc(sizeof(int) * size);
for (int i=1; i<argc; ++i) {
data[i-1] = atoi(argv[i]);
}
interleave(data, size);
for (int i=0; i<size; ++i) {
printf("%d ", data[i]);
}
printf("\n");
delete data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment