Rotate your phone or change to desktop for better experience

Rotate your phone or change to desktop for better experience

selection sort || DS

 #include <stdio.h>


void display(int arr[], int n);

void selectionsort(int arr[], int n) {
    int position, temp;

    for (int i = 0; i < (n - 1); i++) {
        position = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[position] > arr[j]) {
                position = j;
            }
        }

        if (position != i) {
            // swap
            temp = arr[i];
            arr[i] = arr[position];
            arr[position] = temp; // Fix: Assign temp to arr[position], not arr[i]
        }
    }

    display(arr, n);
}

void display(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d\n", arr[i]);
    }
}

int main() {
    int n;

    printf("Enter the number of elements\n");
    scanf("%d", &n);
    int arr[n];
    printf("Enter the elements\n");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    selectionsort(arr, n); // Fix: Don't print the result here, as the function already displays the sorted array
display(arr,n);
    return 0;
}

Post a Comment

0 Comments