OneBite.Dev - Coding blog in a bite size

reverse arrays items in java

Code snippet on how to reverse arrays items in java

public static void reverseArray(int[] arr) 
{ 
    int start = 0; 
    int end = arr.length - 1; 
  
    while (start < end) 
    { 
        int temp = arr[start]; 
        arr[start] = arr[end]; 
        arr[end] = temp; 
        start++; 
        end--; 
    } 
} 

This code is used to reverse the order of the elements in an int array. The code starts off by creating two variables, start and end, which are used as indices in the array. The start index will begin at the first element in the array and the end index will be set to the last element in the array. A while loop will be set up that will keep running as long as the start index is less than the end index. Inside the loop, the element at the start index will be temporarily stored in a variable called ‘temp’, then the element at the end index will be assigned to the element at the start index and the element at the start index will be assigned to the element at the end index using the ‘temp’ variable. Finally, the start and end indices will be incremented and decremented respectively before the loop is run again. This process will keep running until the start index is greater than the end index and the elements in the array will be reversed.

java