allstar allstar - 15 days ago 8
C Question

Slide Algorithm

I'm looking for algorithm scroll number For example;

I have an array which has the numbers 1,2,3,4. I want to make my new array 4,1,2,3.

Does anyone know how to do this?

But not just for D[4]; it can be 1,2,3,4,5,6,7

Answer

The in place version:

#include <stdio.h>

void swap(int* a, int* b){
int temp = *a;
*a = *b;
*b = temp;
}

int main(){
int i;
int size = 4;
int arr[4] = {1,2,3,4};
for(i = 0; i < size; i++){
  printf("%d, ", arr[i]);
}
printf("\n");
for( i = size-1; i > 0; i-- ){
  swap(&arr[i],&arr[i-1]);
}
for(i = 0; i < size; i++){
  printf("%d, ", arr[i]);
}