C Program to sort the given list using insertion sort technique:
ALGORITHM :
Step 1: Start
Step 2: Input the number of elements (n) and the list of elements (my_list).
Step 3: Repeat the following steps for i = 1 to n-1:
a. Set current_element to my_list[i].
b. Set j to i-1.
c. While j >= 0 and my_list[j] > current_element:
i. Move the element at index j one position ahead (i.e., my_list[j+1] = my_list[j]).
ii. Decrement j by 1.
d. Place current_element in the correct position (i.e., my_list[j+1] = current_element).
Step 4: Display the sorted list.
Step 5: End
SOURCE CODE :
#include <stdio.h>
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int n;
printf("Enter the number of elements in the list: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
insertionSort(arr, n);
printf("Sorted list: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
No comments:
Post a Comment