Created
June 5, 2025 12:02
-
-
Save MurageKibicho/50de3c0fc470ddc56388904a44a411fc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#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