From 5ebdb96702a22c4597bbc60ace623f2b11fc28e9 Mon Sep 17 00:00:00 2001 From: Veekshitha11 Date: Tue, 29 Oct 2024 23:40:09 +0530 Subject: [PATCH] Create insertionSort.c Insertion sort is a simple and efficient sorting algorithm that builds a sorted array one element at a time. It works by iterating through an input list and for each element, inserting it into its correct position in the already sorted portion of the list. --- C/insertionSort.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C/insertionSort.c diff --git a/C/insertionSort.c b/C/insertionSort.c new file mode 100644 index 0000000..4592b8a --- /dev/null +++ b/C/insertionSort.c @@ -0,0 +1,37 @@ +#include + +void insertionSort(int arr[], int n) { + int i, key, j; + for (i = 1; i < n; i++) { + key = arr[i]; + j = i - 1; + + // Move elements of arr[0..i-1], that are greater than key, + // to one position ahead of their current position + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} + +void printArray(int arr[], int n) { + for (int i = 0; i < n; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +int main() { + int arr[] = {12, 11, 13, 5, 6}; + int n = sizeof(arr) / sizeof(arr[0]); + + printf("Original array: \n"); + printArray(arr, n); + + insertionSort(arr, n); + + printf("Sorted array: \n"); + printArray(arr, n); + return 0; +}