C Online Compiler
Example: Replace Array Elements by Rank in C Program
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Replace Array Elements by Rank #include
#include
// Required for qsort // Structure to hold an element's value and its original index typedef struct { int value; int original_index; } Element; // Comparison function for qsort: sorts Element structs by their 'value' int compareElements(const void *a, const void *b) { return ((Element *)a)->value - ((Element *)b)->value; } // Function to replace array elements by their ranks void replaceWithRanks(int arr[], int n) { // Step 1: Create an array of Element structs Element *elements = (Element *)malloc(n * sizeof(Element)); if (elements == NULL) { fprintf(stderr, "Memory allocation failed!\n"); return; } // Step 2: Populate the elements array with values and original indices for (int i = 0; i < n; i++) { elements[i].value = arr[i]; elements[i].original_index = i; } // Step 3: Sort the elements array based on their values qsort(elements, n, sizeof(Element), compareElements); // Step 4: Create a temporary array to store ranks based on original indices int *ranks = (int *)malloc(n * sizeof(int)); if (ranks == NULL) { fprintf(stderr, "Memory allocation failed!\n"); free(elements); return; } // Step 5: Assign ranks to the original positions int current_rank = 1; for (int i = 0; i < n; i++) { // If it's not the first element and current value is different from previous if (i > 0 && elements[i].value != elements[i-1].value) { current_rank++; } // Store the current_rank at the original position of this element ranks[elements[i].original_index] = current_rank; } // Step 6: Replace the original array elements with their calculated ranks for (int i = 0; i < n; i++) { arr[i] = ranks[i]; } // Step 7: Free dynamically allocated memory free(elements); free(ranks); } int main() { // Original array int arr[] = {10, 20, 10, 30, 5, 20}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); // Replace elements with their ranks replaceWithRanks(arr, n); printf("Array with ranks: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); // Another example int arr2[] = {7, 3, 7, 1, 9, 3}; int n2 = sizeof(arr2) / sizeof(arr2[0]); printf("Original array 2: "); for (int i = 0; i < n2; i++) { printf("%d ", arr2[i]); } printf("\n"); replaceWithRanks(arr2, n2); printf("Array 2 with ranks: "); for (int i = 0; i < n2; i++) { printf("%d ", arr2[i]); } printf("\n"); return 0; }
Output
Clear
ADVERTISEMENTS