Chapter 3: array [5 common algorithm] - [6 Reverse]

① Custom reversal

 

public static void reverse(int[] arr) {

      for(int x=0; x<arr.length/2; x++) {

          int temp = arr[x];

          arr[x] = arr[arr.length-1-x];

          arr[arr.length-1-x] = temp;

      }

}

//recommend

public static void reverse2(int[] arr) {

      for(int start=0,end=arr.length-1; start<=end; start++,end--) {

          int temp = arr[start];

          arr[start] = arr[end];

          arr[end] = temp;

      }

}

 

 

Collections.reverseOrder () usage (reverse the natural order)
 

String[] a = {"a","b","c"};

Arrays.sort(a,Collections.reverseOrder());

System.out.println(Arrays.asList(a));

③Apache Commons Lang library

int[] arr= { 1, 2, 3, 4, 5 };  

ArrayUtils.reverse(intArray);  

System.out.println(Arrays.toString(intArray));   //[5, 4, 3, 2, 1]

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/Lucky-stars/p/11010129.html