Thursday, February 4, 2021

How to reverse an Array without using extra memory



public class ReverseArrayWithoutExtraMemory {

	public static void main(String[] args) {
		int arr[] = {1,2,3,4,5,6};
		int swapArray[] = new ReverseArrayWithoutExtraMemory().swapArray(arr);
		for (int i : swapArray) {
			System.out.print(i+" ");
		}
	}

	public int[] swapArray(int[] arr) {
		int startIndex=0;
		
		int lastIndex= arr.length-1;
		while(lastIndex > startIndex) {
			
			swapItem(arr, startIndex, lastIndex);
			lastIndex--;
			startIndex++;
		}
		return arr;
	}

	public void swapItem(int[] arr, int startIndex, int lastIndex) {
		int temp = arr[startIndex];
		arr[startIndex] = arr[lastIndex];
		arr[lastIndex] = temp;
		
	}

}

Output:-
6 5 4 3 2 1

No comments:

Post a Comment

How to find middle node of LinkedList without using extra memory in java

To find the middle node of a LinkedList without using extra memory in Java, you can use the "tortoise and hare" algorithm. This al...