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


Source Code

#include <stdio.h>
#include <string.h>

//Array size defined
#define SIZE 8

//Insertion sort function
int ins_sort(int a[],int n){
    int j,key,i,k;

    printf("Array_Before_Insertion_Sort:\n");
    for(i=0;i<n;i++)
            printf("%d ",a[i]);
        printf("\n\n");
    
    //Sorting Algorithm
    for(j=1;j<n;j++){
        
        key=a[j];
        printf("\nKey- %d\n",key);
        i=j-1;
        
        while(i>=0 && a[i]>key){
            a[i+1]=a[i];
            i=i-1;
            for(k=0;k<n;k++)
                printf("%d ",a[k]);
            printf("\n");
        }
        a[i+1]=key;
        for(i=0;i<n;i++)
            printf("%d ",a[i]);
        printf("\n");
    }
}

//Main Function
void main(){
    
    int arr[SIZE];
    int i;
    for(i=0;i<SIZE;i++)
        scanf("%d",&arr[i]);
    
    //Call to Insertion Sort
    ins_sort(arr, SIZE);

    printf("\n\n");
    printf("Array_After_Insertion_Sort:\n");
    for(i=0;i<SIZE;i++)
        printf("%d ",arr[i]);
}


    STDIN Input - 8 7 6 5 4 3 2 1



Output


Array_Before_Insertion_Sort:
8 7 6 5 4 3 2 1 


Key- 7
8 8 6 5 4 3 2 1 
7 8 6 5 4 3 2 1 

Key- 6
7 8 8 5 4 3 2 1 
7 7 8 5 4 3 2 1 
6 7 8 5 4 3 2 1 

Key- 5
6 7 8 8 4 3 2 1 
6 7 7 8 4 3 2 1 
6 6 7 8 4 3 2 1 
5 6 7 8 4 3 2 1 

Key- 4
5 6 7 8 8 3 2 1 
5 6 7 7 8 3 2 1 
5 6 6 7 8 3 2 1 
5 5 6 7 8 3 2 1 
4 5 6 7 8 3 2 1 

Key- 3
4 5 6 7 8 8 2 1 
4 5 6 7 7 8 2 1 
4 5 6 6 7 8 2 1 
4 5 5 6 7 8 2 1 
4 4 5 6 7 8 2 1 
3 4 5 6 7 8 2 1 

Key- 2
3 4 5 6 7 8 8 1 
3 4 5 6 7 7 8 1 
3 4 5 6 6 7 8 1 
3 4 5 5 6 7 8 1 
3 4 4 5 6 7 8 1 
3 3 4 5 6 7 8 1 
2 3 4 5 6 7 8 1 

Key- 1
2 3 4 5 6 7 8 8 
2 3 4 5 6 7 7 8 
2 3 4 5 6 6 7 8 
2 3 4 5 5 6 7 8 
2 3 4 4 5 6 7 8 
2 3 3 4 5 6 7 8 
2 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 


Array_After_Insertion_Sort:
1 2 3 4 5 6 7 8 

Comments

Popular posts from this blog

Selection Sort with step-by-step Output

Ahahaha! This blog