/*CODER: Santostefano Giovanni*/ #include typedef int type; /* CODER: Santostefano Giovanni (http://santostefanogiovanni.blogspot.com) * Questa funzione si occupa di shiftare * un segmento di un array in una certa direzione * selezionata (utilizzando memcpy anzich�funzioni di swap) dall'utente mediante i seguenti * parametri: * type *a -> array generico * int begin -> inizio del segmento * int end -> fine del segmento * int shift -> number of position to shift */ void ShiftSeg(type *a, int begin, int end, int shift) { type *temp=NULL, *temp2=NULL; int dir=0; if(!a)return; /*control if the shift is module of the segment size *and then return */ if(shift<0) { dir=-1; shift=shift*(-1); } else dir=1; if((end-begin+1)>shift) { if((begin-end+1)%shift==0)return; } else if(shift%(end-begin+1)==0) { return; } else shift=shift%(end-begin+1); temp=malloc(shift*sizeof(type)); temp2=malloc((end-begin-shift)*sizeof(type)); if(dir==1) { memcpy(temp,a+end-shift+1,shift*sizeof(type)); memcpy(temp2,a+begin,(end-begin-shift+1)*sizeof(type)); memcpy(a+begin+shift,temp2,(end-begin-shift+1)*sizeof(type)); memcpy(a+begin,temp,shift*sizeof(type)); } else { memcpy(temp,a+begin,shift*sizeof(type)); memcpy(temp2,a+begin+shift,(end-begin-shift+1)*sizeof(type)); memcpy(a+begin,temp2,(end-begin-shift+1)*sizeof(type)); memcpy(a+end-shift+1,temp,shift*sizeof(type)); } free(temp); free(temp2); } /*CLIENT TEST*/ int main() { type a[]={1,2,3,4,5,6,7,8,9}; int i=0; ShiftSeg(a,0,8,-3); for(;i<9;i++) { printf("%d,",a[i]); } printf("\n"); ShiftSeg(a,0,8,3); for(i=0;i<9;i++) { printf("%d,",a[i]); } printf("\n"); return 1; }