0

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

3
  • It's not clear what you're trying to do with key, but returning p+1 is almost certainly wrong. Try removing key and all the code related to key. Commented Apr 3, 2021 at 20:44
  • Hello @user3386109, I actually provide key there in case if loop doesn't find any lesser value than the first element(i.e temp or *(p+i) ) then, it just return address of that element...But unfortunetly there I write (p+1) instead of (p+i)...But I also tried with removing whole code related to key, But I got same unsorted output. Commented Apr 3, 2021 at 20:55
  • You need to initialize the index, e.g. int *index = p + i;. That way, if no smaller value is found, the code will return p + i. Commented Apr 3, 2021 at 20:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.