Arrays sort in ascending and descending order
Example:
Input: arr = { 1, 4, 6, 7, 3, 2, 8 }; Output: [8, 7, 6, 4, 3, 2, 1]
Approach: Array sort in descending order
Java
import java.util.Arrays;public class ArraySortAscDesc {public static void main(String[] args) {int[] arr = { 1, 4, 6, 7, 3, 2, 8 };arr = selectionSorting(arr, arr.length);System.out.println(Arrays.toString(arr));}static int[] selectionSorting(int[] arr, int N) {for (int i = 0; i < N; i++) {int min = i;for (int j = i + 1; j < N; j++) {if (arr[min] < arr[j]) {min = j;}}// Swapping elementint tmp = arr[min];arr[min] = arr[i];arr[i] = tmp;}return arr;}}
Approach: Array sort in ascending order
Java
import java.util.Arrays;public class ArraySortAscDesc {public static void main(String[] args) {int[] arr = { 1, 4, 6, 7, 3, 2, 8 };arr = selectionSorting(arr, arr.length);System.out.println(Arrays.toString(arr));}static int[] selectionSorting(int[] arr, int N) {for (int i = 0; i < N; i++) {int min = i;for (int j = i + 1; j < N; j++) {if (arr[min] > arr[j]) {min = j;}}// Swapping elementint tmp = arr[min];arr[min] = arr[i];arr[i] = tmp;}return arr;}}
Approach: Array sort in ascending order using inbuild method
Java
import java.util.Arrays;public class ArraySortAscDesc {public static void main(String[] args) {int[] arr = { 1, 4, 6, 7, 3, 2, 8 };Arrays.sort(arr);System.out.println(Arrays.toString(arr));}}
Approach: Array sort from position to position
Java
import java.util.Arrays;public class ArraySortAscDesc {public static void main(String[] args) {int[] arr = { 1, 4, 6, 7, 3, 2, 8 };Arrays.sort(arr,2,5);System.out.println(Arrays.toString(arr));}}// [1, 4, 3, 6, 7, 2, 8]
Approach: Object Array sort in descending order
Java
import java.util.Arrays;public class ArraySortAscDesc {public static void main(String[] args) {Integer[] arr = { 1, 4, 6, 7, 3, 2, 8 };Arrays.sort(arr, Collections.reverseOrder());System.out.println(Arrays.toString(arr));}}
No comments:
Post a Comment