publicclassReverseArray{publicstaticvoidmain(String[]args){// Array with some elementint[]myArray={10,22,33,11,88,9,2};// reverse loop and printingfor(inti=myArray.length-1;i>=0;i--){System.out.print(myArray[i]+" ");}}}
Method 2 - Using Array List
// Method 2 Reverse an array using array listpublicclassReverseArray{publicstaticvoidmain(String[]args){// Array ListArrayList<Integer>myArray=newArrayList<Integer>();myArray.add(10);myArray.add(21);myArray.add(13);myArray.add(14);myArray.add(51);// reverse array and methodCollections.reverse(myArray);System.out.println(myArray);}}
Method 3 - Two Pointers and Swap
// Method 3 Reverse with swappublicclassReverseArray{publicstaticvoidmain(String[]args){// Array with some elementint[]myArray={10,22,33,11,88,9,2};intstart=0;intend=myArray.length-1;inttemp=0;// looping and swappingwhile(end>start){temp=myArray[start];myArray[start]=myArray[end];myArray[end]=temp;end--;start++;}for(inti:myArray){System.out.print(i+" ");}}}
This seems to be C++, not JavaScript. In JavaScript, you'd have
constmyArray=[10,22,33,11,88,9,2]// native (will change the original reference)myArray.reverse()console.log(myArray)myArray.reverse()// change it back// functionalconstfunctionalReversedMyArray=myArray.reduce((result,item)=>[item,...result],[])console.log(functionalReversedMyArray)// imperativeconstimperativeReversedMyArray=[]for(constindexinmyArray){imperativeReversedMyArray.unshift(myArray[index])}console.log(imperativeReversedMyArray)// recursiveconstrecursiveArrayReversal=(inputArray,partiallyReversed=[])=>inputArray.length?recursiveArrayReversal(inputArray.slice(1),[inputArray[0],...partiallyReversed]):partiallyReversedconstrecursiveReversedMyArray=recursiveArrayReversal(myArray)console.log(recursiveReversedMyArray)
Top comments (5)
This seems to be C++, not JavaScript. In JavaScript, you'd have
Thanks :) That was JAVA :)
Here is a crazy one 😀:
Great work bro!
:) thanks