1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-12-08 00:45:29 +01:00

feat(solutions): add sorting-algorithms/c/insertion-sort

This commit is contained in:
Divlo 2021-06-29 22:07:12 +02:00
parent 6d7011f3a7
commit 3a28a3b52d
No known key found for this signature in database
GPG Key ID: 185ED2F15F104E52
3 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,7 @@
# sorting-algorithms/c/insertion-sort
Created by [@Divlo](https://github.com/Divlo) on 29 June 2021.
| Algorithm | Best Case | Average Case | Worst Case |
| ----------------------------------------------------------- | ----------- | ------------ | ----------- |
| [Insertion sort](https://wikipedia.org/wiki/Insertion_sort) | O(n) | O(n²) | O(n²) |

View File

@ -0,0 +1,6 @@
#ifndef INSERTION_SORT_H
#define INSERTION_SORT_H
void insertion_sort(int *numbers, const int length);
#endif

View File

@ -0,0 +1,32 @@
#include <stdio.h>
#include <stdlib.h>
#include "insertion_sort.h"
int main() {
int *numbers = malloc(25000 * sizeof(int));
int current_number;
int index_input = 0;
while (scanf("%d", &current_number) != EOF) {
numbers[index_input] = current_number;
index_input += 1;
}
insertion_sort(numbers, index_input);
for (int index = 0; index < index_input; index++) {
printf("%d\n", numbers[index]);
}
free(numbers);
return 0;
}
void insertion_sort(int numbers[], const int length) {
for (int index_1 = 1; index_1 < length; index_1++) {
int current = numbers[index_1];
int index_2 = index_1 - 1;
while (index_2 >= 0 && numbers[index_2] > current) {
numbers[index_2 + 1] = numbers[index_2];
index_2 -= 1;
}
numbers[index_2 + 1] = current;
}
}