# Array reversal

In this post I would be discussing array reversal. Array reversal means reversing the order of elements in an array. An  array can be reversed using various approaches, the simplest is by using another array. But, using another array requires double memory and hence is not a very good approach. Another approach is of reversing an array is to swap the first element with the last element, second element with the second last element and so on. The process of swapping would stop once we reach the halfway mark since all the elements would be swapped by then. Let us see the process with the help of an example:

```1 2 3 4 5 6
^         ^
6 2 3 4 5 1
^     ^

6 5 3 4 2 1
^ ^

6 5 4 3 2 1```

The caret sign (^) marks the elements being swapped. The Java program for array reversal is as follows:

```class ReverseArray{
public static void displayArray( int []a ){
for( int n: a ){
System.out.print( n + " " );
}
System.out.println();
}
public static int[] reverseArrayIterative( int []a ){
int half = a.length / 2, temp;
for(int i = 0; i <= half ; i++ ){
temp = a[ i ];
a[ i ] = a[ a.length-i-1 ];
a[ a.length-i-1 ] = temp;
}
return a;
}
public static void main( String args[] ){
int []a = { 1, 2, 3, 4, 5, 6 };
displayArray( a );
a = reverseArrayIterative(a);
}
}```

In the above Java program on array reversal the function displayArray() is a helper function to display the array. The displayArray function uses enhanced for loop which I have already discussed in an earlier post. The function reverseArrayIterative() accepts an integer array as an argument and returns the array after sorting as discussed above.

The above program on reversing an array can also be done using recursion. We can use two variables, say left and right, such that left is increased and right is decreased as the elements at position left and right are swapped. The base condition or the exit condition be when left >  right. The Java program for array reversal using recursion as discussed above is as follows:

```class ReverseArray{
public static void displayArray( int []a ){
for( int n: a ){
System.out.print( n + " " );
}
System.out.println();
}
public static int[] reverseArrayRecursive( int []a ){
return reverseArrayRecursive(a, 0, a.length - 1 );
}
private static int[] reverseArrayRecursive( int []a, int left, int right ){
if( left > right ) return a;
else{
int temp = a[ left ];
a[ left ] = a[ right ];
a[ right ] = temp;
return reverseArrayRecursive(a, left+1, right-1 );
}
}
public static void main( String args[] ){
int []a = { 1, 2, 3, 4, 5, 6 };
int []b = { 1, 2, 3, 4, 5 };
a = reverseArrayRecursive( a );
b = reverseArrayRecursive( b );
displayArray( a );
displayArray( b );
}
}```

Note that the function reverseArrayRecursive() is overloaded. The function which is public is the one which would be invoked for reversing the array. The function which is private would be invoked by the public function with the correct initial values. The private function would recursively call itself to reverse the array as discussed above. I would like to emphasize here, that iterative method of array reversal is more efficient due to time and memory overheads in case of recursion.

As usual, the main function has purposely been kept to minimum and its expected that students will write appropriate input/output statements as per the requirement.

This site uses Akismet to reduce spam. Learn how your comment data is processed.
{"ft_lang_label":"__label__en","ft_lang_prob":0.7704068,"math_prob":0.9633723,"size":3301,"snap":"2020-34-2020-40","text_gpt3_token_len":816,"char_repetition_ratio":0.14801334,"word_repetition_ratio":0.14666666,"special_character_ratio":0.27627993,"punctuation_ratio":0.14128728,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98965675,"pos_list":[0,1,2],"im_url_duplicate_count":[null,6,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-08-06T10:37:45Z\",\"WARC-Record-ID\":\"<urn:uuid:6c93bdb6-5d62-4490-b7cf-ba586a3464aa>\",\"Content-Length\":\"55815\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:ee67019d-f27a-4257-afb6-282d340b2276>\",\"WARC-Concurrent-To\":\"<urn:uuid:7004da09-62fa-49bf-a273-b80b568becf7>\",\"WARC-IP-Address\":\"35.168.49.211\",\"WARC-Target-URI\":\"https://www.vinaysingh.info/array-reversal/\",\"WARC-Payload-Digest\":\"sha1:74MJHHGGQHOP6KZTXXXR6KJV5KR3XUVN\",\"WARC-Block-Digest\":\"sha1:JI7UGYLEEGAUYW6HKKVCOSSUZBRBRAYT\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-34/CC-MAIN-2020-34_segments_1596439736902.24_warc_CC-MAIN-20200806091418-20200806121418-00565.warc.gz\"}"}