Friday, October 10, 2025
HomeData Modelling & AIJavascript Program to Split the array and add the first part to...

Javascript Program to Split the array and add the first part to the end | Set 2

Given an array and split it from a specified position, and move the first part of 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.

 

A O(n*k) solution is discussed here
This problem can be solved in O(n) time using the reversal algorithm discussed below, 
1. Reverse array from 0 to n – 1 (where n is size of the array). 
2. Reverse array from 0 to n – k – 1. 
3. Reverse array from n – k to n – 1.
 

Javascript




<script>
// Javascript program to Split the array and
// add the first part to the end
  
/* Function to reverse arr[] from index start to end*/
function rvereseArray(arr, start, end)
{
    while (start < end)
    {
        let temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}
  
// Function to print an array
function printArray(arr, size)
{
    for (let i = 0; i < size; i++)
        document.write(arr[i] + " ");
}
  
/* Function to left rotate arr[] of size n by k */
function splitArr(arr, k, n)
{
    rvereseArray(arr, 0, n - 1);
    rvereseArray(arr, 0, n - k - 1);
    rvereseArray(arr, n - k, n - 1);
}
  
/* Driver program to test above functions */
let arr = new Array( 12, 10, 5, 6, 52, 36 );
let n = arr.length;
let k = 2;
  
// Function calling
splitArr(arr, k, n);
printArray(arr, n);
  
// This code is contributed
// by _saurabh_jaiswal
</script>


Output: 
 

5 6 52 36 12 10 

 

Please refer complete article on Split the array and add the first part to the end | Set 2 for more details!

Last Updated :
24 Jan, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

RELATED ARTICLES

Most Popular

Dominic
32349 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6715 POSTS0 COMMENTS
Nicole Veronica
11878 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6837 POSTS0 COMMENTS
Ted Musemwa
7097 POSTS0 COMMENTS
Thapelo Manthata
6792 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS