C Online Compiler
Example: Sort Array by Another Array's Order (qsort with Lookup)
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Sort Array by Another Array's Order (qsort with Lookup) #include <stdio.h> #include <stdlib.h> // For qsort #include <limits.h> // For INT_MAX (to mark elements not in order array) #include <string.h> // For memset // A global array to store the ranks/priorities. // We assume array elements are non-negative and within a reasonable range (e.g., 0-100). // Adjust MAX_VAL based on the maximum possible value in your arrays. #define MAX_VAL 101 // Assuming elements are 0-100 int rank_map[MAX_VAL]; // Comparison function for qsort int compare(const void *a, const void *b) { int val1 = *(const int *)a; int val2 = *(const int *)b; int rank1 = (val1 >= 0 && val1 < MAX_VAL) ? rank_map[val1] : INT_MAX; int rank2 = (val2 >= 0 && val2 < MAX_VAL) ? rank_map[val2] : INT_MAX; // If ranks are different, sort by rank (lower rank first) if (rank1 != rank2) { return rank1 - rank2; } else { // If ranks are the same (either both are in order_array B and have same rank, // which means they are the same value, or both are NOT in order_array B), // then sort by their actual value in ascending order. return val1 - val2; } } int main() { int arr_A[] = {10, 30, 20, 50, 40, 20}; int n_A = sizeof(arr_A) / sizeof(arr_A[0]); int order_B[] = {20, 10, 40}; int n_B = sizeof(order_B) / sizeof(order_B[0]); // Step 1: Initialize rank_map. // Set all ranks to INT_MAX, indicating elements not in order_B. for (int i = 0; i < MAX_VAL; i++) { rank_map[i] = INT_MAX; } // Alternative: memset(rank_map, 0xFF, sizeof(rank_map)); // Sets to -1 if unsigned, or large positive if signed char // Step 2: Populate rank_map based on order_B. // Assign increasing ranks (0, 1, 2...) to elements in order_B. for (int i = 0; i < n_B; i++) { if (order_B[i] >= 0 && order_B[i] < MAX_VAL) { rank_map[order_B[i]] = i; } } // Step 3: Print original array for comparison. printf("Original Array A: ["); for (int i = 0; i < n_A; i++) { printf("%d%s", arr_A[i], (i == n_A - 1) ? "" : ", "); } printf("]\n"); // Step 4: Sort arr_A using qsort with the custom comparator. qsort(arr_A, n_A, sizeof(int), compare); // Step 5: Print sorted array. printf("Sorted Array A: ["); for (int i = 0; i < n_A; i++) { printf("%d%s", arr_A[i], (i == n_A - 1) ? "" : ", "); } printf("]\n"); return 0; }
Output
Clear
ADVERTISEMENTS