03 March 2026

Insertion Sort

 #include<stdio.h>

#include<conio.h>


void main()

{

int arr[99], no, i, j, temp;

clrscr();


printf("Enter number of elements: ");

scanf("%d", &no);


printf("Enter %d integers: ", no);

for (i = 0; i < no; i++)

{

scanf("%d", &arr[i]);

}


for (i = 1; i < no; i++)

{

temp = arr[i];

j = i - 1;


while (j >= 0 && arr[j] > temp)

{

arr[j + 1] = arr[j]; // Move element to the right

j = j - 1;           // Move to the previous element

}

// Move origional element into its correct position

arr[j + 1] = temp;

}


printf("Sorted elements:\n");

for (i = 0; i < no; i++)

{

printf("%d ", arr[i]);

}

printf("\n");


getch();

}


No comments:

Post a Comment