Skip to content

Instantly share code, notes, and snippets.

@jimexist
Created May 4, 2013 12:28
Show Gist options
  • Select an option

  • Save jimexist/5517350 to your computer and use it in GitHub Desktop.

Select an option

Save jimexist/5517350 to your computer and use it in GitHub Desktop.
A simple code to shift an array of integers to the left for a number of times
#import <stdio.h>
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
/* Precondition: n > 0 */
void reverse(int arr[], int n) {
int i;
for (i=0; i<n/2; ++i) {
swap(arr+i, arr+n-i-1);
}
}
/* Precondition: n > 0 */
void shift(int data[], int n, int i) {
i = i % n;
if (i < 0) {
i += n;
}
if (i == 0) {
return;
}
reverse(data, i);
reverse(data+i, (n-i));
reverse(data, n);
}
int main(int arg, char* argv[]) {
int data[] = {1,2,3,4,5,6};
shift(data, 6, -5);
int i;
for (i=0; i<6; ++i) {
printf("%d ", data[i]);
}
return 0;
}
@jimexist

jimexist commented May 4, 2013

Copy link
Copy Markdown
Author

Example from Programming Pearls

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment