</>EmbeddedInterview
← All problems · Arrays & Searching

Reverse a Sample Buffer In Place

Easy

Reverse n samples in place with no extra array. Implement void reverse_samples(int *a, size_t n).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Swap mirrored positions.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>

void reverse_samples(int *a, size_t n)
{
    for(size_t i=0;i<n/2;++i){int t=a[i];a[i]=a[n-1-i];a[n-1-i]=t;}
}

Only half the array needs to be visited.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    int a[]={1,2,3,4};
    CHECK((reverse_samples(a,4),a[0]==4 && a[3]==1 && a[1]==3));
    CHECK((reverse_samples(NULL,0),1));
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}