Php 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.
Â
PHP
<?php
function rvereseArray(& $arr , $start , $end )
{
while ( $start < $end )
{
$temp = $arr [ $start ];
$arr [ $start ] = $arr [ $end ];
$arr [ $end ] = $temp ;
$start ++;
$end --;
}
}
function printArray(& $arr , $size )
{
for ( $i = 0; $i < $size ; $i ++)
echo $arr [ $i ] . " " ;
}
function splitArr(& $arr , $k , $n )
{
rvereseArray( $arr , 0, $n - 1);
rvereseArray( $arr , 0, $n - $k - 1);
rvereseArray( $arr , $n - $k , $n - 1);
}
$arr = array ( 12, 10, 5, 6, 52, 36 );
$n = sizeof( $arr );
$k = 2;
splitArr( $arr , $k , $n );
printArray( $arr , $n );
?>
|
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
Share your thoughts in the comments
Please Login to comment...