So I made this program using only for loops. I was just trying to see what would happen if I use for instead of while but the loop is only working for comparison between one sorted and unsorted element not the sorted elements before it.

#include <stdio.h>

void insertion(int arr[], int y) {
    int h, z, temp, x;
    for (z = 1; z <= y; z++) {
        for (x = z - 1; x >= 0; x--) {
            if (arr[x] >= arr[z]) {
                temp = arr[z];
                arr[z] = arr[x];
                arr[x] = temp;
            }
        }
    }
    for (h = 0; h < y; h++) {
        printf("\n %d", arr[h]);
    }
}

void main() {
    int arr[50];
    int x;
    printf("Enter the numbers of elemnts");
    scanf("%d", &x);
    printf("Enter the elements");
    for (int z = 0; z < x; z++)
        scanf("%d", &arr[z]);
    insertion(arr, x);
}

1 Answers

1
Aviv Goll On Best Solutions

I think you have some off-by-1 errors and comparing to the wrong element (compared to:

i ← 1
while i < length(A)
    j ← i
    while j > 0 and A[j-1] > A[j]
        swap A[j] and A[j-1]
        j ← j - 1
    end while
    i ← i + 1
end while

from: https://en.wikipedia.org/wiki/Insertion_sort#Algorithm)

Try the following:

#include<stdio.h>
void insertion (int arr[],int y)
{
    int h,z,temp,x;
    for(z = 1; z < y; z++)
    {
        for(x=z; x > 0 && arr[x-1] > arr[x]; x--)
        {
            temp=arr[x];
            arr[x]=arr[x-1];
            arr[x-1]=temp;
        }
    }
    for(h=0;h<y;h++)
    {
        printf("\n %d",arr[h]);
    }
}
void main()
{
    int arr[50];
    int x;
    printf("Enter the numbers of elemnts: ");
    scanf("%d",&x);
    printf("Enter the elements\n");
    for(int z=0;z<x;z++)
        scanf("%d",&arr[z]);
    insertion(arr,x);
}