Search code examples
carrayspointersselection-sort

Using selection sort with array of pointers


I am currently trying to sort an array of pointers using selection sort, but with no success. I need to sort an array of int values with only pointers. I have already stored values in the array, and only thing left to do is to sort these values.

Here is my code:

void fill_rand_ver2(int *pointer, int size)
{
int randNbr;
int *i;

for(i = pointer; i < (pointer + size); i++)
{
    randNbr = (rand()%10)+1;
    *i = randNbr;
}
}

// sort array with help of selection sort using pointer
void sort_ver2(int *pointer, int size)
{
int *i, *j, swap;

for(i = pointer; i < (pointer + size); i++)
{
    for(j = i + 1; j < (pointer + size); j++)
    {
        if(*j < *i)
        {
            swap = *i;
            *i = *j;
            *j = swap;
        }
    }
}
}

// print out both arrays using pointer
void print_values_ver2(char *string, int *pointer, int size)
{
int *i;

printf("%s", string);
printf("\n");

for(i = pointer; i < (pointer + size); i++)
{
    printf("%d,", *i);
}
printf("\n\n");
}

When I run the program and print data, the entered values are not sorted and remain at the same place. I would appreciate any help given.


Solution

  • I believe you want to sort by value, not by address, so it should be:

    void sort_ver2(int *pointer, int size)
    {
        int *i, *j, swap;
        int *end = NULL;
    
        if(size < 2 || pointer == NULL)
            return;
    
        end = pointer + size - 1;
    
        for(i = pointer; i < end; i++)
        {
            for(j = i + 1; j <= end; j++)
            {
                if(*j < *i)
                {
                    swap = *i;
                    *i = *j;
                    *j = swap;
                }
            }
        }
    }
    

    Even if you would like to sort by address, your if statement is incorrect, as j is always greater than i in your code.

    EDIT: added end variable to address issue with incorrect range of the inner for loop. Credits to @WhozCraig.