There is a given array and split it from a specified position, and move the first part of the array add to the end.
Input : arr[] = {12, 10, 5, 6, 52, 36}
k = 2
Output : arr[] = {5, 6, 52, 36, 12, 10}
public class Split_array_add_first_part_to_the_end {
public static void main(String[] args) {
int a[]= {12,10,5,6,52,36};
int i,j;
int n=a.length;
int x=a[0];
for(i=0;i<n-1;i )
{
int temp=a[i];
a[i]=a[i 1];
temp=a[i];
}
a[n-1]=x;
for(i=0;i<n; i)
{
System.out.println(a[i]);
}
}
}
a[n-1]=x; ->this replace the 12 how to rotate the 10th value
I am getting output like this 10 5 6 52 36 12
Please explain the flow of execution and what mistake I made
CodePudding user response:
int a[] = {12, 10, 5, 6, 52, 36};
// use int declaration in for-loop.
for (int k = 0; k < 2; k ) {
for (int i = 0; i < a.length - 1; i ) {
int temp = a[i]; // swap number to end per iteration
a[i] = a[i 1];
a[i 1] = temp;
}
}
for (int i = 0; i < a.length; i) {
System.out.println(a[i]);
}
You almost had it. This solution is working I have seen that you declared the index as variable outside the for-loop (not necessary). I would recommend you to start smaller and break problems down each.
Main thing I guess you wanted to do is cycle through the array per k times iterations. I would starting on progamming:
- Printing each item;
- Swapping one item;
- Swapping items each index (means swapped to end)
- Just do it k-times by surround the loop with another one (k-loop)
My approach would be using Collections and rotate to shorten it more
Integer a[] = {12, 10, 5, 6, 52, 36};
List<Integer> list = Arrays.asList(a);
Collections.rotate(list, -2); // Rotate the list backwards by two elements
System.out.println(Arrays.toString(a));