Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,700 questions

57,013 answers

573 users

How to sort array of strings using function pointer for sort order in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

int ascending_compare(char* p1, char* p2) {
    return strcmp(p1, p2);
}

int descending_compare(char* p1, char* p2) {
    return strcmp(p2, p1);
}

void sort(char* p[], int size, int sort_type) {
    int (*compare) (char* s1, char* s2);

    compare = (sort_type) ? ascending_compare : descending_compare;

    for (int i = 1; i < size; i++) {
        for (int j = 0; j < size - 1; j++) {
            if (compare(p[j], p[j + 1]) > 0) {
                char* pstring = p[j];
                p[j] = p[j + 1];
                p[j + 1] = pstring;
            }
        }
    }
}

int main(void)
{
    char* array[] = { "java",
                      "c++",
                      "c#",
                      "python",
                      "c" };

    int size = sizeof(array) / sizeof(array[0]);

    sort(array, size, 1); // ascending order
    for (int i = 0; i < size; i++)
        puts(array[i]);
    
    printf("\n");

    sort(array, size, 0); // descending order
    for (int i = 0; i < size; i++)
        puts(array[i]);

    return 0;
}





/*
run:

c
c#
c++
java
python

python
java
c++
c#
c

*/

 



answered May 9, 2023 by avibootz
edited May 10, 2023 by avibootz

Related questions

1 answer 196 views
1 answer 346 views
1 answer 218 views
2 answers 316 views
...