Sort First Half in Ascending Order and Second Half in Descending
Understanding Sorting Strategy
This task involves sorting the first half of an array in ascending order and the second half in descending order.
We will explore three different methods to achieve this in Java.
Method 1: Using Built-in Sorting
This method splits the array and sorts each part separately.
import java.util.*; public class SortHalf { public static void sortHalf(int[] arr) { int mid = arr.length / 2; Arrays.sort(arr, 0, mid); Arrays.sort(arr, mid, arr.length, Collections.reverseOrder()); } public static void main(String[] args) { Integer[] arr = {7, 2, 5, 3, 9, 8, 6, 4}; sortHalf(arr); System.out.println(Arrays.toString(arr)); } }
[2, 3, 5, 7, 9, 8, 6, 4]
Method 2: Using Bubble Sort
This method implements sorting manually using bubble sort.
import java.util.*; public class SortHalf { public static void bubbleSort(int[] arr, int start, int end, boolean ascending) { for (int i = start; i < end - 1; i++) { for (int j = start; j < end - 1 - (i - start); j++) { if ((ascending && arr[j] > arr[j + 1]) || (!ascending && arr[j] < arr[j + 1])) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } public static void sortHalf(int[] arr) { int mid = arr.length / 2; bubbleSort(arr, 0, mid, true); bubbleSort(arr, mid, arr.length, false); } public static void main(String[] args) { int[] arr = {7, 2, 5, 3, 9, 8, 6, 4}; sortHalf(arr); System.out.println(Arrays.toString(arr)); } }
[2, 3, 5, 7, 9, 8, 6, 4]
Method 3: Using Insertion Sort
This method sorts both halves separately using insertion sort.
import java.util.*; public class SortHalf { public static void insertionSort(int[] arr, int start, int end, boolean ascending) { for (int i = start + 1; i < end; i++) { int key = arr[i]; int j = i - 1; while (j >= start && ((ascending && arr[j] > key) || (!ascending && arr[j] < key))) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } public static void sortHalf(int[] arr) { int mid = arr.length / 2; insertionSort(arr, 0, mid, true); insertionSort(arr, mid, arr.length, false); } public static void main(String[] args) { int[] arr = {7, 2, 5, 3, 9, 8, 6, 4}; sortHalf(arr); System.out.println(Arrays.toString(arr)); } }
[2, 3, 5, 7, 9, 8, 6, 4]