Source code:
/*Insertion sort is a sorting algorithm in which the elements are transferred one at a time to the right position. Here the first element in the array is considered as sorted, even if it is an unsorted array. Then each element in the array is checked with the previous elements, resulting in a growing sorted output list. With each iteration, the sorting algorithm removes one element at a time and finds the appropriate location within the sorted array and inserts it there. The iteration continues until the whole list is sorted. First an array of size 10 will be taken. We will fill it by reading 10 integers. You need to write the logic of Selection Sort. The final output will be sorted output in Ascending Order.*/
#include <stdio.h>
int main()
{
int n=10, array[10], i, j, t;
/* Read Array Elements*/
printf("Enter the array: ");
for (i = 0; i < n; i++) {
scanf("%d", &array[i]);
}
for (i = 1 ; i <= n - 1; i++) {
j = i;
while ( j > 0 && array[j-1] > array[j]) {
t = array[j];
array[j] = array[j-1];
array[j-1] = t;
j--;
}
}
printf("The sorted output in ascending order:\n");
for (i = 0; i <= n - 1; i++) {
printf("%d\n", array[i]);
}
return 0;
}
No comments:
Post a Comment