Complementary task for topic: 3

M Nemeth · 2023-08-29 15:21:04.617219'

Arrays: Sort: selection sort

Arrays: Sort: selection sort

Write a C program that allows the user to enter 5 integers. The program should store the integers in an array and then sort in ascending order using selection sort

Hint: Selection sort means that you always find the minimum for the next element in the array from the remaining part of the array

Solution
#include 

#define SIZE 5

int main() {
    int numbers[SIZE];
    int temp, min_index;

    printf("Enter %d integers:\n", SIZE);

    // Read integers from the user and store them in the numbers array
    for (int i = 0; i < SIZE; i++) {
        scanf("%d", &numbers[i]);
    }

    // Sort the array using selection sort
    for (int i = 0; i < SIZE - 1; i++) {
        min_index = i;
        for (int j = i + 1; j < SIZE; j++) {
            if (numbers[j] < numbers[min_index]) {
                min_index = j;
            }
        }

        // Swap the current element with the smallest element found
        temp = numbers[i];
        numbers[i] = numbers[min_index];
        numbers[min_index] = temp;
    }

    // Print the sorted array
    printf("\nSorted Array:\n");
    for (int i = 0; i < SIZE; i++) {
        printf("%d ", numbers[i]);
    }

    return 0;
}



Explanation

< < previous    next > >