Insertion Sort
#include <stdio.h>
#include <stdlib.h>
// Function Prototypes
void insertionSort(int *arr, int len);
void insertionSort(int *arr, int len) {
int i, j, hand;
for (i = 1; i < len; i++) {
hand = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > hand) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = hand;
}
}
void printArr(int *arr, int len) {
for (int i = 0; i < len; i++)
printf("%d ", arr[i]);
printf("\n\n");
}
int main(void) {
int len = 20;
int *arr = malloc(len * sizeof(int));
for (int i = 0; i < len; i++) {
arr[i] = rand() % 100;
}
printf("Printing Array...\n\n");
printArr(arr, len);
printf("Applying Insertion Sort...\n\n");
insertionSort(arr, len);
printf("Printing Sorted Array...\n\n");
printArr(arr, len);
free(arr);
return 0;
}
Academic Notice: The code shown here is provided solely as a learning reference. Copying and pasting is intentionally disabled to encourage independent practice. Students should implement solutions on their own to demonstrate understanding. This material is not intended for direct submission in assignments.
Additionally: This code was written by a former CS1 student and may not reflect your professor’s intended solution or instructional approach. For coursework, students are expected to follow examples, conventions, and requirements presented in class and in professor-assigned materials.