Reverse Array :
Reverse the given array by using temporary variable.
Input : 50, 40, 30, 20, 10
Output : 10, 20, 30, 40, 50
/** * @author StrangeCoder */public class ReverseArray { private static void reverse(int[] array, int length) { int reverseArray[] = new int[length]; int j = length; for (int i = 0; i < length; i++) { reverseArray[j-1] = array[i]; j = j - 1; } System.out.println("Printing reversed array : \n"); for (int i = 0; i < reverseArray.length; i++) { System.out.println(reverseArray[i]); } } public static void main(String[] args) { int array[] = {50, 40, 30, 20, 10}; reverse(array, array.length); }}
Output :
Printing reversed array : 1020304050
Rotate an array :
Rotate the given array with respect to the number of times.
Input : 10, 20, 30, 40, 50
Output : 30, 40, 50, 10, 20
/** * @author StrangeCoder */public class RotateArray { private static int[] rotate(int[] arr, int numberOfTimes, int length) { //Rotate the given array by n times toward right for(int i = 0; i < numberOfTimes; i++) { //Stores the last element of array int last = arr[arr.length-1]; for(int j = arr.length-1; j > 0; j--){ //Shift element of array by one arr[j] = arr[j-1]; } //Last element of array will be added to the start of array. arr[0] = last; } return arr; } public static void main(String[] args) { int[] array = {10, 20, 30, 40, 50}; int numberOfTimes = 2; System.out.println(rotate(array, numberOfTimes, array.length)); }}






Leave a comment