Created
May 4, 2013 12:28
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example from Programming Pearls