Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Selection Sort with Step-by-Step Output

Tech 1

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...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

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