How to sort Array in Ascending, Descending and Mixed mode in Java?
UPDATED: 05 February 2015
Tags:
Array
,
Comparator
,
Interview
java.util.Arrays class provides many options for sorting an Array. We will sort Array in Ascending, Descending and Mixed mode(1st/first to kth in Ascending order and k+1th to nth/last in Descending order, you can choose different position for 1st,kth and nth).
In addition this question was asked in leading Multi National Company(MNC). Its worth understanding code for future interview of yours.
Source Code
Output
In addition this question was asked in leading Multi National Company(MNC). Its worth understanding code for future interview of yours.
Source Code
public class SortArray { public static void main(String[] args) { Integer[] intSortArrayAscending = {25, 9, 23, 1, 4, 90, 99}; Integer[] intSortArrayDescending = {25, 9, 23, 1, 4, 90, 99}; Integer[] intSortArrayMixedMode = {25, 9, 23, 1, 4, 90, 99}; /* Sort Array in Ascending order */ Arrays.sort(intSortArrayAscending); /* Print array */ System.out.print("Ascending order: "); for (int i : intSortArrayAscending) { System.out.print(i + ","); } System.out.println("\n------------------------"); /* Sort Array in Descending order */ SortArray objSortArray = new SortArray(); /* Use Comparator to sort Array in Descending order */ Arrays.sort(intSortArrayDescending, objSortArray.comparatorDescending()); /* Print array */ System.out.print("Descending order: "); for (int i : intSortArrayDescending) { System.out.print(i + ","); } System.out.println("\n------------------------"); System.out.println("Mixed mode sorting:"); /** * Mixed mode Sorting * Sort 1st/first position to kth in Ascending order * and * Sort k+1th position to nth/last in Descending order */ /* I used middle point as pivotPoint */ int pivotPosition = intSortArrayMixedMode.length / 2; System.out.println("Ascending order from element 1 to " + pivotPosition); System.out.println("Descending order from element " + (pivotPosition + 1) + " to " + intSortArrayMixedMode.length); /* Arrays.sort(int[] a, int fromIndex, int toIndex) */ Arrays.sort(intSortArrayMixedMode, 0, pivotPosition); /* sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) */ Arrays.sort(intSortArrayMixedMode, pivotPosition, intSortArrayMixedMode.length, objSortArray.comparatorDescending()); /* Print array */ for (int i : intSortArrayMixedMode) { System.out.print(i + ","); } } /** * Comparator for Descending order */ public Comparator<Integer> comparatorDescending() { return new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (o1 < o2) { return 1; } else { return -1; } } }; } }
Output
Ascending order: 1,4,9,23,25,90,99, ------------------------ Descending order: 99,90,25,23,9,4,1, ------------------------ Mixed mode sorting: Ascending order from element 1 to 3 Descending order from element 4 to 7 9,23,25,99,90,4,1,
Tags:
Array
,
Comparator
,
Interview
0 comments :