/*有n個數,使前面各數順序向後移動m個位置,最後m個數變成最前面m個數。如12345後移3位之後變為34512.*/ #includevoid reverse_array(int *a, int len, int start, int end); int main (int argc, char *argv[]) { int i; int array[10] = {1,2,3,4,5,6,7,8,9,0}; reverse_array(array,10, 0, 9); reverse_array(array,10, 0, 2); reverse_array(array,10, 3, 9); for(i=0; i<10; i++){ printf("%d,",array[i]); } putchar('\n'); return 0; } void reverse_array(int *a, int len, int start, int end) { int tmp; if(end <= len){ while(start < end){ tmp = a[start]; a[start] = a[end]; a[end] = tmp; start++; end--; } } }
分析:第一步,間將怎個數組倒敘排列變為 0,9,8,7,6,5,4,3,2,1
第二步,根據輸入的移動次數,將前m (此處m = 3)個倒敘,現在數組為8,9,0,7,6,5,4,3,2,1
第三步,將後面幾個倒敘, 8,9,0,1,2,3,4,5,6,7