Selection Sort with step-by-step Output

Source Code

#include <stdio.h>

//defining the constant ASIZE as array's size

#define ASIZE 10

void main(){

    int i,j,key;
    
    //var just for displaying the in-between arrays
    int l;
    
    //unsorted array
    int a[ASIZE]={0,5,4,8,1,9,7,3,6,2};
    
    // printing the unsorted array
    printf("Unsorted Array: ");
    for(i=0;i<ASIZE;i++)
        printf("%d ",a[i]);
    printf("\n\n");
    
   //start of Selection Sort
   
   //traversing the whole array
    for(i=0;i<ASIZE;i++){
     
        //taking position of i in a key variable
        key=i;
                //gives the smaller element everytime one is found
        printf("\nSmallest Element= %d", a[key]);
        
       //inner loop to find position of smallest digit
       
       //traversing the unsorted array
        for(j=i+1;j<ASIZE;j++){
            if(a[key]>a[j]){
                key=j;                                        printf("\n\tsub-Smallest Element= %d", a[key]);
            }
        }
    
     
       //if key is not the same as i
        if(key!=i){
            a[i]=a[i]+a[key];
            a[key]=a[i]-a[key];
            a[i]=a[i]-a[key];
        }
    
     
       //printing the in-between array with swapped
        //items bracketed for easy understanding
        printf("\n\n");
        for(l=0;l<ASIZE;l++){
            if(l==key || l==i)
                printf("[");
            printf("%d",a[l]);
            if(l==key || l==i)
                printf("]");
            printf(" ");
        }
        printf("\n\n");
    }
    //Printing the sorted array
    printf("\n\nSorted Array: ");
    for(i=0;i<ASIZE;i++)
        printf("%d ",a[i]);
}

Output


Unsorted Array: 0 5 4 8 1 9 7 3 6 2 


Smallest Element= 0

[0] 5 4 8 1 9 7 3 6 2 


Smallest Element= 5
 sub-Smallest Element= 4
 sub-Smallest Element= 1

0 [1] 4 8 [5] 9 7 3 6 2 


Smallest Element= 4
 sub-Smallest Element= 3
 sub-Smallest Element= 2

0 1 [2] 8 5 9 7 3 6 [4] 


Smallest Element= 8
 sub-Smallest Element= 5
 sub-Smallest Element= 3

0 1 2 [3] 5 9 7 [8] 6 4 


Smallest Element= 5
 sub-Smallest Element= 4

0 1 2 3 [4] 9 7 8 6 [5] 


Smallest Element= 9
 sub-Smallest Element= 7
 sub-Smallest Element= 6
 sub-Smallest Element= 5

0 1 2 3 4 [5] 7 8 6 [9] 


Smallest Element= 7
 sub-Smallest Element= 6

0 1 2 3 4 5 [6] 8 [7] 9 


Smallest Element= 8
 sub-Smallest Element= 7

0 1 2 3 4 5 6 [7] [8] 9 


Smallest Element= 8

0 1 2 3 4 5 6 7 [8] 9 


Smallest Element= 9

0 1 2 3 4 5 6 7 8 [9] 



Sorted Array: 0 1 2 3 4 5 6 7 8 9 

Comments

Popular posts from this blog

Ahahaha! This blog

Insertion Sort with Run-Time Input & step-by-step Output