C Online Compiler
Example: Sort Array by Another Array's Order (Brute-Force)
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Sort Array by Another Array's Order (Brute-Force) #include <stdio.h> #include <stdlib.h> // For malloc, qsort #include <stdbool.h> // For bool type // Comparison function for standard numeric sort of remaining elements int compare_int(const void *a, const void *b) { return (*(int *)a - *(int *)b); } 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: Create a boolean array to track visited elements in arr_A. // Initialize all to false. bool visited[n_A]; for (int i = 0; i < n_A; i++) { visited[i] = false; } // Step 2: Create a new array for the sorted result. int *result_arr = (int *)malloc(n_A * sizeof(int)); if (result_arr == NULL) { perror("Failed to allocate memory"); return 1; } int result_idx = 0; // Step 3: Iterate through order_B and populate result_arr. for (int i = 0; i < n_B; i++) { int target_val = order_B[i]; for (int j = 0; j < n_A; j++) { if (!visited[j] && arr_A[j] == target_val) { result_arr[result_idx++] = arr_A[j]; visited[j] = true; // Mark as visited } } } // Step 4: Collect remaining elements from arr_A (those not in order_B). int *remaining_elements = (int *)malloc(n_A * sizeof(int)); if (remaining_elements == NULL) { perror("Failed to allocate memory"); free(result_arr); return 1; } int remaining_count = 0; for (int i = 0; i < n_A; i++) { if (!visited[i]) { remaining_elements[remaining_count++] = arr_A[i]; } } // Step 5: Sort the remaining elements. qsort(remaining_elements, remaining_count, sizeof(int), compare_int); // Step 6: Append sorted remaining elements to result_arr. for (int i = 0; i < remaining_count; i++) { result_arr[result_idx++] = remaining_elements[i]; } // Step 7: Print original and sorted arrays. printf("Original Array A: ["); for (int i = 0; i < n_A; i++) { printf("%d%s", arr_A[i], (i == n_A - 1) ? "" : ", "); } printf("]\n"); printf("Sorted Array A: ["); for (int i = 0; i < n_A; i++) { printf("%d%s", result_arr[i], (i == n_A - 1) ? "" : ", "); } printf("]\n"); // Step 8: Free dynamically allocated memory. free(result_arr); free(remaining_elements); return 0; }
Output
Clear
ADVERTISEMENTS