Split the array

There is a given array and split it from a specified position, and move the first part of the array add to the end.
Examples:

Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end . Input : arr[] = {3, 1, 2} k = 1 Output : arr[] = {1, 2, 3} Explanation : Split from index 1 and first part add to the end.

Simple Solution
We one by one rotate array.

  • C++

// CPP program to split array and move first

// part to end.

#include <bits/stdc++.h>

using namespace std;

void splitArr( int arr[], int n, int k)

{

`` for ( int i = 0; i < k; i++) {

`` // Rotate array by 1.

`` int x = arr[0];

`` for ( int j = 0; j < n - 1; ++j)

`` arr[j] = arr[j + 1];

`` arr[n - 1] = x;

`` }

}

// Driver code

int main()

{

`` int arr[] = { 12, 10, 5, 6, 52, 36 };

`` int n = sizeof (arr) / sizeof (arr[0]);

`` int position = 2;

`` splitArr(arr, 6, position);

`` for ( int i = 0; i < n; ++i)

`` printf ( "%d " , arr[i]);

`` return 0;

}

Output:

5 6 52 36 12 10

Time complexity of the above solution is O(nk).
Another approach: Another approach is to make a temporary array with double the size and copy our array element into a new array twice .and then copy the element from the new array to our array by taking the rotation as starting index up to the length of our array.
Below is the implementation of the above approach.

  • C++

// CPP program to split array and move first

// part to end.

#include <bits/stdc++.h>

using namespace std;

// Function to spilt array and

// move first part to end

void splitArr( int arr[], int length, int rotation)

{

`` int tmp[length * 2] = {0};

`` for ( int i = 0; i < length; i++)

`` {

`` tmp[i] = arr[i];

`` tmp[i + length] = arr[i];

`` }

`` for ( int i = rotation; i < rotation + length; i++)

`` {

`` arr[i - rotation] = tmp[i];

`` }

}

// Driver code

int main()

{

`` int arr[] = { 12, 10, 5, 6, 52, 36 };

`` int n = sizeof (arr) / sizeof (arr[0]);

`` int position = 2;

`` splitArr(arr, n, position);

`` for ( int i = 0; i < n; ++i)

`` printf ( "%d " , arr[i]);

`` return 0;

}

Output:

5 6 52 36 12 10