0% found this document useful (0 votes)
5 views2 pages

C Program for Insertion Sort Algorithm

The document contains a C program that implements the Insertion Sort algorithm. It defines functions for sorting an array and printing the array before and after sorting. The sample output demonstrates the sorting of an array from unsorted to sorted order.

Uploaded by

myjio0536
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

C Program for Insertion Sort Algorithm

The document contains a C program that implements the Insertion Sort algorithm. It defines functions for sorting an array and printing the array before and after sorting. The sample output demonstrates the sorting of an array from unsorted to sorted order.

Uploaded by

myjio0536
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C Program: Insertion Sort

#include <stdio.h>

// Function to perform Insertion Sort

void insertionSort(int arr[], int n) {

int i, key, j;

for (i = 1; i < n; i++) {

key = arr[i]; // Take the current element

j = i - 1;

// Move elements greater than key one position ahead

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = key; // Place the key at its correct position

// Function to print array

void printArray(int arr[], int n) {

for (int i = 0; i < n; i++)

printf("%d ", arr[i]);

printf("\n");

// Driver code

int main() {

int arr[] = {12, 11, 13, 5, 6};

int n = sizeof(arr)/sizeof(arr[0]);

printf("Original array: ");


C Program: Insertion Sort
printArray(arr, n);

insertionSort(arr, n);

printf("Sorted array: ");

printArray(arr, n);

return 0;

Sample Output
Original array: 12 11 13 5 6

Sorted array: 5 6 11 12 13

You might also like