How do I reverse an int array in Java?

前端 未结 30 2361
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 07:18

I am trying to reverse an int array in Java.

This method does not reverse the array.

for(int i = 0; i < validData.length; i++)
{
    int temp =          


        
30条回答
  •  孤街浪徒
    2020-11-21 08:06

    2 ways to reverse an Array .

    1. Using For loop and swap the elements till the mid point with time complexity of O(n/2).

      private static void reverseArray() {
      int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
      
      for (int i = 0; i < array.length / 2; i++) {
          int temp = array[i];
          int index = array.length - i - 1;
          array[i] = array[index];
          array[index] = temp;
      }
      System.out.println(Arrays.toString(array));
      

      }

    2. Using built in function (Collections.reverse())

      private static void reverseArrayUsingBuiltInFun() {
      int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
      
      Collections.reverse(Ints.asList(array));
      System.out.println(Arrays.toString(array));
      

      }

      Output : [6, 5, 4, 3, 2, 1]

提交回复
热议问题