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 C.
Method 1: Using Standard Sorting
This method sorts the array by manually splitting and sorting it.
#include <stdio.h> #include <stdlib.h> int compareAsc(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int compareDesc(const void *a, const void *b) { return (*(int*)b - *(int*)a); } void sort_half(int arr[], int size) { int mid = size / 2; qsort(arr, mid, sizeof(int), compareAsc); qsort(arr + mid, size - mid, sizeof(int), compareDesc); } int main() { int arr[] = {7, 2, 5, 3, 9, 8, 6, 4}; int size = sizeof(arr) / sizeof(arr[0]); sort_half(arr, size); for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } return 0; }
2 3 5 7 9 8 6 4
Method 2: Using Bubble Sort
This method implements sorting manually using bubble sort.
#include <stdio.h> void bubbleSort(int arr[], int start, int end, int 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; } } } } void sort_half(int arr[], int size) { int mid = size / 2; bubbleSort(arr, 0, mid, 1); bubbleSort(arr, mid, size, 0); } int main() { int arr[] = {7, 2, 5, 3, 9, 8, 6, 4}; int size = sizeof(arr) / sizeof(arr[0]); sort_half(arr, size); for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } return 0; }
2 3 5 7 9 8 6 4
Method 3: Using Insertion Sort
This method sorts both halves separately using insertion sort.
#include <stdio.h> void insertionSort(int arr[], int start, int end, int 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; } } void sort_half(int arr[], int size) { int mid = size / 2; insertionSort(arr, 0, mid, 1); insertionSort(arr, mid, size, 0); } int main() { int arr[] = {7, 2, 5, 3, 9, 8, 6, 4}; int size = sizeof(arr) / sizeof(arr[0]); sort_half(arr, size); for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } return 0; }
2 3 5 7 9 8 6 4