Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Selection Sort with Step-by-Step Output

Tech May 1 23

Selection Sort Algorithm Implementation

This program implements the selection sort algorithm to sort an array of integers in ascending order, displaying the array state after each sorting step.

Input Format

The first line contains a positive integer n (n ≤ 10). The second line contains n integres separated by spaces.

Output Format

After each sorting step, output the current state of the array from index 0 to n-1, with elements separated by spaces and no trailing spaces.

Example Input

4
5 1 7 6

Example Output

1 5 7 6
1 5 7 6
1 5 6 7

Implemantation Code

#include <stdio.h>

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

int main() {
    int count;
    scanf("%d", &count);
    
    int numbers[count];
    for (int i = 0; i < count; i++) {
        scanf("%d", &numbers[i]);
    }
    
    if (count == 1) {
        printf("%d\n", numbers[0]);
        return 0;
    }
    
    for (int current = 0; current < count - 1; current++) {
        int minIndex = current;
        
        for (int j = current + 1; j < count; j++) {
            if (numbers[j] < numbers[minIndex]) {
                minIndex = j;
            }
        }
        
        int temp = numbers[minIndex];
        numbers[minIndex] = numbers[current];
        numbers[current] = temp;
        
        displayArray(numbers, count);
    }
    
    return 0;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Comprehensive Guide to Hive SQL Syntax and Operations

This article provides a detailed walkthrough of Hive SQL, categorizing its features and syntax for practical use. Hive SQL is segmented into the following categories: DDL Statements: Operations on...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.