Skip to content

Commit

Permalink
Create insertionSort.c
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Veekshitha11 authored and x0lg0n committed Oct 30, 2024
1 parent 64234f4 commit 5ebdb96
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions C/insertionSort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#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;

// 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;
}

0 comments on commit 5ebdb96

Please sign in to comment.