Ko thực hiện hàm swap trong Selection Sort

Cho mình hỏi là mình code phần mà nó ko thực hiện hàm swap. Vậy lỗi ở đây là gì?

#include <stdio.h>
#include <stdlib.h>

void swap(int *a, int *b)
{
    int t;
    t =* a;
    *a = *b;
    *b = t;
}

void selecSort(int *a, int k, int n)
{
    int *min, i, loc;
    min = &a[k];
    loc = k;
    if(k < n)
    {
        for(i = k+1; i < n; i++)
        {
            if (*min >= a[i])
            {
                min = &a[i];
                loc = i;
            }
        }
        swap(&a[loc], min);
        selecSort(a, k+1, n);
    }
}

int main()
{
    int a[50], i, n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    for(i = 0; i < n; i++) scanf("%d",&a[i]);
    selecSort(a, 0, n);
    printf("Sorted array\n");
    for(i = 0; i < n; i++) printf("%d \t",a[i]);
    return 0;
}

No noi ban bi loi gi

Mình thấy thằng swap(&a[loc], min) swap chính nó với nó luôn ấy.
Đây là code đã sửa: swap(&a[k], min)

2 Likes

Cảm ơn bạn, mình tìm thấy lỗi này rồi :slight_smile:

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?