OneCompiler

Completed code solution

170

import java.util.Arrays;

public class Main {

/**
 * Split an array and move the first part at the end
 *
 *
 * ### PART 1 : Reverse an array
 *
 * For given array with 10 elements:
 * [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
 *
 * When reversed with reverseArray(arr, 0,9) should produce:
 * [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 *
 * ### PART 2 : Split an array by given position and move the first part at the end
 *
 * Given the array
 * [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 *
 * When split at position [2], splitAndSwap(arr, 2) should produce the following:
 *
 * [2, 3, 4, 5, 6, 7, 8, 9, 0, 1]
 */

public static void main(String[] args) {
    int arr[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};



    printArray(arr);

    reverseArray(arr, 0, arr.length - 1);

    printArray(arr);

    splitAndSwap(arr, 2);

    printArray(arr);
}

static void reverseArray(int arr[], int start, int end) {
    int[] reversedArrayValues = new int[end - start + 1];
    int counter = 0;

    for (int i = end; i >= start; i--) {
        reversedArrayValues[counter] = arr[i];
        counter++;
    }

    counter = 0;
    for (int i = start; i <= end; i++) {
        arr[i] = reversedArrayValues[counter];
        counter++;
    }
}


static void splitAndSwap(int arr[], int position) {
    reverseArray(arr, 0, position - 1);
    reverseArray(arr, position, arr.length - 1);
    reverseArray(arr, 0, arr.length - 1);
}

static void printArray(int arr[]) {
    System.out.println(Arrays.toString(arr));
}

}