Pointer Array Sorter
C
Medium
2 views
Problem Description
Create an array of pointers pointing to different strings. Sort the strings without moving the strings - just reorder the pointers.
Official Solution
#include <stdio.h>
#include <string.h>
/* Swap two pointers */
void swap(char **a, char **b) {
char *temp = *a;
*a = *b;
*b = temp;
}
/* Sort array of string pointers in ascending order */
void sortStrings(char *arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (strcmp(arr[i], arr[j]) > 0) { // compare strings
swap(&arr[i], &arr[j]); // swap pointers
}
}
}
}
int main() {
char *strings[] = {"banana", "apple", "mango", "grape", "cherry"};
int n = sizeof(strings) / sizeof(strings[0]);
printf("Original strings:n");
for (int i = 0; i < n; i++)
printf("%sn", strings[i]);
sortStrings(strings, n);
printf("nSorted strings:n");
for (int i = 0; i < n; i++)
printf("%sn", strings[i]);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!