overhead computer science
#include <stdio.h>
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
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 arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: \n");
printArray(arr, n);
insertionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Explanation:
- #include <stdio.h>
: Includes the standard input-output library in C for functions like printf()
and scanf()
.
void printArray(int arr[], int size)
: A function to print an array. It takes an arrayarr
and its sizesize
as arguments.void insertionSort(int arr[], int n)
: A function implementing the insertion sort algorithm. It takes an arrayarr
and its sizen
as arguments.int main()
: The starting point of execution for the C program.int arr[] = {12, 11, 13, 5, 6};
: Declares an arrayarr
containing integers.int n = sizeof(arr) / sizeof(arr[0]);
: Calculates the number of elements in the arrayarr
.printf("Unsorted array: \n");
: Prints a message indicating the unsorted array.printArray(arr, n);
: Calls theprintArray
function to print the unsorted array.insertionSort(arr, n);
: Calls theinsertionSort
function to sort the arrayarr
using the insertion sort algorithm.printf("Sorted array: \n");
: Prints a message indicating the sorted array.printArray(arr, n);
: Calls theprintArray
function to print the sorted array.return 0;
: Indicates successful execution of the program.