Skip to content

Instantly share code, notes, and snippets.

@Xitsa
Created August 15, 2017 04:15
Show Gist options
  • Select an option

  • Save Xitsa/59541f671faab6b8784265cd6e6cc71d to your computer and use it in GitHub Desktop.

Select an option

Save Xitsa/59541f671faab6b8784265cd6e6cc71d to your computer and use it in GitHub Desktop.
Simple program for testing recursive algorithm of array shift
#include <stdio.h>
#include <cassert>
#include <memory>
// compile as g++ --std=c++11 e.cxx
// Array size
const size_t N = 35;
// print [left, right]
void print(const char* message, int* array, size_t left, size_t right)
{
printf("%s: ", message);
for (size_t f = left; f <= right; ++f) {
printf("%2d", array[f]);
if (f != right) {
printf(", ");
}
}
printf("\n");
}
void eswap(int* array, size_t index1, size_t index2, size_t count)
{
int* i1 = array + index1;
int* i2 = array + index2;
for (int f = 0; f < count; ++f) {
int tmp = *i1;
*i1 = *i2;
*i2 = tmp;
++i1;
++i2;
}
}
// preparing interval [l1..r1) to prettyprint
void print_interval(char* buffer, size_t bufsize, size_t l1, size_t r1)
{
const ssize_t size = r1 - l1;
if (size > 1) {
snprintf(buffer, bufsize, "[%d..%d]"
, l1
, r1 - 1
);
} else if (size == 1) {
snprintf(buffer, bufsize, "[%d]"
, l1
);
} else {
snprintf(buffer, bufsize, "Wrong interval!!!");
}
}
void debug_swapi_iter_call(int* array, size_t l1_param, size_t r1_param, size_t l2_param, size_t r2_param)
{
if (true) return;
//xDebug
char Left[128];
char Right[128];
print_interval(Left, sizeof(Left), l1_param, r1_param);
print_interval(Right, sizeof(Right), l2_param, r2_param);
printf(" swapi: %s and %s\n"
, Left
, Right
);
}
// swap [l..m) and [m..r)
void swapi_iter_opt(int* array, size_t l, size_t m, size_t r)
{
ssize_t lsize = m - l;
ssize_t rsize = r - m;
for (;;) {
assert(l <= m);
assert(m <= r);
if (lsize <= 0) return;
if (rsize <= 0) return;
//xDebug
debug_swapi_iter_call(array, l, m, m, r);
if (lsize < rsize) {
r -= lsize;
rsize -= lsize;
eswap(array, l, r, lsize);
// now [r..r+lsize) is in place
} else {
eswap(array, l, m, rsize);
l += rsize;
lsize -= rsize;
// now [l-rsize..m) is in place
}
}
}
void swap(int* array, size_t left)
{
swapi_iter_opt(array, 0, left, N);
}
std::unique_ptr<int[]> get_array(size_t size)
{
std::unique_ptr<int[]> array(new int[size]);
for (int f = 0; f < size; ++f) {
array[f] = f + 1;
}
return array;
}
int main(int argc, char* [])
{
for (size_t k = 0; k < N; ++k) {
std::unique_ptr<int[]> array(get_array(N));
swap(array.get(), k);
print("Swapped array", array.get(), 0, N - 1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment