Following example shows how to sort elements of an array in reverse order using reverseOrder() method of Collections class and sort() method of Arrays class in java.util.package .
Output:
Elements of Array:
3 ,2 ,5 ,7 ,1 ,4 ,6 ,
Elements of Array (Sorted):
1 ,2 ,3 ,4 ,5 ,6 ,7 ,
Elements of Array (Sorted in REVERSE):
7 ,6 ,5 ,4 ,3 ,2 ,1 ,
Note:Arrays.sort(intArray,Collections.reverseOrder()); cannot be used with array of primitives
import java.util.Arrays;
import java.util.Collections;
public class ArrayReverse{
public static void main(String args[]){
Integer[] intArray = new Integer[7];
intArray[0]=new Integer(3);
intArray[1]=new Integer(2);
intArray[2]=new Integer(5);
intArray[3]=new Integer(7);
intArray[4]=new Integer(1);
intArray[5]=new Integer(4);
intArray[6]=new Integer(6);
System.out.println("\n Elements of Array:\n");
for(int i:intArray)
System.out.print(i+" ,");
System.out.println("\n Elements of Array (Sorted):\n");
Arrays.sort(intArray);
for(int i:intArray)
System.out.print(i+" ,");
Arrays.sort(intArray,Collections.reverseOrder());
System.out.println("\n Elements of Array (Sorted in REVERSE):\n");
for(int i:intArray)
System.out.print(i+" ,");
}
}
import java.util.Collections;
public class ArrayReverse{
public static void main(String args[]){
Integer[] intArray = new Integer[7];
intArray[0]=new Integer(3);
intArray[1]=new Integer(2);
intArray[2]=new Integer(5);
intArray[3]=new Integer(7);
intArray[4]=new Integer(1);
intArray[5]=new Integer(4);
intArray[6]=new Integer(6);
System.out.println("\n Elements of Array:\n");
for(int i:intArray)
System.out.print(i+" ,");
System.out.println("\n Elements of Array (Sorted):\n");
Arrays.sort(intArray);
for(int i:intArray)
System.out.print(i+" ,");
Arrays.sort(intArray,Collections.reverseOrder());
System.out.println("\n Elements of Array (Sorted in REVERSE):\n");
for(int i:intArray)
System.out.print(i+" ,");
}
}
Output:
Elements of Array:
3 ,2 ,5 ,7 ,1 ,4 ,6 ,
Elements of Array (Sorted):
1 ,2 ,3 ,4 ,5 ,6 ,7 ,
Elements of Array (Sorted in REVERSE):
7 ,6 ,5 ,4 ,3 ,2 ,1 ,
Note:Arrays.sort(intArray,Collections.reverseOrder()); cannot be used with array of primitives
I would like to know your comments and if you liked the article then please share it on social networking buttons.
thanks for sharin'
ReplyDelete