NoobCoder
NoobCoder

Reputation: 60

Why this C-Program for selection sort gives wrong output?

This program for selection sort gives unfavorable output, I tried a lot but unable to find my mistake, The output, I'm getting through this is not sorted, one or more elements are at wrong position(or they are not sorted)...Please help me to find my mistake.

#include <stdio.h>

void swap(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}

int *get_least(int *p, int i, int count)
{
int temp = *(p + i), key = 0;
int *index;

for (i; i < count; i++)
{

    if (temp > *(p + i))
    {
        temp = *(p + i);
        index = (p + i);
        key++;
    }
}

if (key == 0)
{
    return (p + 1);
}

return (index);
}

void sel_sort(int *p, int count)
{
for (int i = 0; i < count - 1; i++)
{
    swap((p + i), get_least(p, i, count));
}
}

int main()
{
int num[10], count;

printf("ENTER INPUT LIMIT:\n");
scanf("%d", &count);

printf("ENTER YOUR NUMBERS:\n");
for (int i = 0; i < count; i++)
{
    scanf("%d", &num[i]);
}

sel_sort(num, count);

printf("OUTPUT AFTER SORTING:\n");
for (int i = 0; i < count; i++)
{
    printf("%d ", num[i]);
}

return (0);
}

I'm getting this output: Here

Upvotes: 0

Views: 43

Answers (1)

TheDev05
TheDev05

Reputation: 196

As you mentioned in comments, You want to return address. now, When you return (p+i) as an address, Your i value get changed and holds the last incremented value from for loop, so the returned address is diffrent from what You supposed to return.

Upvotes: 1

Related Questions