Skip to content

Instantly share code, notes, and snippets.

@Jimexist
Created May 4, 2013 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jimexist/5517350 to your computer and use it in GitHub Desktop.
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
Copy link
Author

Jimexist commented May 4, 2013

Example from Programming Pearls

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