简体   繁体   中英

Selection Sort using pointers

I have the following code:

void sortStrings(char strings[5][32])
{
    int i = 0, j = 0, wall = 0;
    int min = i;
    for (int i = wall; i < 5; i++){
        min = i;
        for (j = wall; j < 5; j++){
            if (strcmp(strings[j], strings[min]) < 0){
                min = j;
            }
        }
        swapStrings(strings[min], strings[wall]); 
        wall++; 
    }
}

What this code does is sorts a 2d array of strings by alphabetical order, I have tested it and it works correctly, now my question is how could I implement this code WITHOUT using array operations (aka using pointers and pointer operations only).

This is what I have so far and it is crashing when I try to run it so what am I doing wrong?

{
    int i = 0, j = 0, wall = 0;
    char *p = strings;
    int min;
    for (i = wall; i < 5; i++){
        min = i;
        for (j = wall; j < 5; j++){
            if (*(p + j) < *(p + min)){
                min = j;
            }
        }
        swapStrings(*(p + j),*(p + wall)); 
        wall++; 
    }
}

Here is the swapStrings method I am using for reference:

void swapStrings(char string1[], char string2[])
{
    char temp[32];
    strcpy(temp, string1);
    strcpy(string1, string2);
    strcpy(string2, temp);
}

The expected output is: if I were to enter in 5 strings, lets say they are:

hello
goodbye
how
are
you

It should return:

are
goodbye
hello
how
you

Thank you.

You have two things wrong:

  1. p have to be char** and not char*
  2. Comparing yourself between strings need a loop such:

     int t = 0; while (*(*(p + j)+t) && (*(*(p + j) + t) == *(*(p + min) + t))) t++; if (*(*(p + j) + t) < *(*(p + min) + t)) { min = j; } 

    Maybe you want to write your function for compare.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM