Skip to content

Instantly share code, notes, and snippets.

@MurageKibicho
Created June 5, 2025 12:02
Show Gist options
  • Save MurageKibicho/50de3c0fc470ddc56388904a44a411fc to your computer and use it in GitHub Desktop.
Save MurageKibicho/50de3c0fc470ddc56388904a44a411fc to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
void PrintArray(int arrayLength, int *array)
{
for(int i = 0; i < arrayLength; i++)
{
printf("%3d, ", array[i]);
}
printf("\n");
}
void RotateLeft(int arrayLength, int *array, int n)
{
n = n % arrayLength;
if(n <= 0){return;}
int *temp = malloc(n * sizeof(int));
// Step 1: Store first n elements in temp
for(int i = 0; i < n; i++){temp[i] = array[i];}
// Step 2: Shift remaining elements left
for (int i = n; i < arrayLength; i++){array[i - n] = array[i];}
// Step 3: Copy temp to the end
for (int i = 0; i < n; i++){array[arrayLength - n + i] = temp[i];}
free(temp);
}
void TestRotateLeft()
{
int array[] = {4,3,5,6,7};
int arrayLength = sizeof(array) / sizeof(int);
PrintArray(arrayLength, array);
RotateLeft(arrayLength, array, 2);
PrintArray(arrayLength, array);
}
int main()
{
TestRotateLeft();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment