ALGORITHM InsertionSort(A[0..n - 1])
//Sorts a given array by insertion sort
//Input: An array A[0..n - 1] of n orderable elements
//Output: Array A[0..n - 1] sorted in nondecreasing order
for i ← 1 to n - 1 do
v ← A[i]
j ← i - 1
while j ≥ 0 and A[j] > v doA[j + 1] ← A[j]j ← j - 1
A[j + 1] ← v
C program:
#include <stdio.h>
#include<stdlib.h>
int main ()
{
int i, j, a[20], n, min, temp;
printf ("ENTER SIZE OF ARRAY\n");
scanf ("%d", &n);
printf ("enter elements\n");
for (i = 0; i < n; i++)
scanf ("%d", &a[i]);
for (i = 1; i <= n - 1; i++)
{
for (j = i; j >=1; j--)
{
if (a[j] < a[j-1])
{
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
printf ("SORTED ELEMENTS ARE:\n");
for (i = 0; i < n; i++)
printf ("%d\t", a[i]);
return 0;
}
Output:
ENTER SIZE OF ARRAY
5
enter elements
1
2
4
5
3
SORTED ELEMENTS ARE:
1 2 3 4 5
//Sorts a given array by insertion sort
//Input: An array A[0..n - 1] of n orderable elements
//Output: Array A[0..n - 1] sorted in nondecreasing order
for i ← 1 to n - 1 do
v ← A[i]
j ← i - 1
while j ≥ 0 and A[j] > v doA[j + 1] ← A[j]j ← j - 1
A[j + 1] ← v
C program:
#include <stdio.h>
#include<stdlib.h>
int main ()
{
int i, j, a[20], n, min, temp;
printf ("ENTER SIZE OF ARRAY\n");
scanf ("%d", &n);
printf ("enter elements\n");
for (i = 0; i < n; i++)
scanf ("%d", &a[i]);
for (i = 1; i <= n - 1; i++)
{
for (j = i; j >=1; j--)
{
if (a[j] < a[j-1])
{
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
printf ("SORTED ELEMENTS ARE:\n");
for (i = 0; i < n; i++)
printf ("%d\t", a[i]);
return 0;
}
Output:
ENTER SIZE OF ARRAY
5
enter elements
1
2
4
5
3
SORTED ELEMENTS ARE:
1 2 3 4 5
0 comments:
Post a Comment