EXNo : 3 INSERTION SORT
Aim:
To implement a Insertion sort algorithm using C.
Algorithm:
1. Start
2. Read the elements from user.
3. If it is the first element, it is already sorted. return 1;
4. Pick next element
5. Compare with all elements in the sorted sub-list
6. Shift all the elements in the sorted sub-list that is greater than the value
to be sorted
7. Insert the value
8. Repeat until list is sorted
9. Stop
Coding:
#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++) {
scanf("%d", &array[c]);
}
for (c = 1 ; c <= n - 1; c++) {
d = c;
while ( d > 0 && array[d] < array[d-1]) {
t = array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++) {
printf("%d\n", array[c]);
}
return 0;
}
Sample Output:
How many elements?
4
Enter 4 elements:
4
5
8
9
Sorted list in ascending order:
4589
[Link] BUBBLE SORT
Aim:
To implement a Bubble sort algorithm using C.
Algorithm:
1. Start
2. Read list of elements
3. for all elements of list check if list[i] > list[i+1]
4. if true swap(list[i], list[i+1])
5. return list
6. Stop
Coding:
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}
Sample Output:
How many elements?
4
Enter 4 elements:
4
5
8
9
Sorted list in ascending order:
4589