mirror of
https://github.com/theoludwig/programming-challenges.git
synced 2024-11-09 22:08:58 +01:00
feat(solutions): add sorting-algorithms/c/insertion-sort
This commit is contained in:
parent
6d7011f3a7
commit
3a28a3b52d
@ -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²) |
|
@ -0,0 +1,6 @@
|
|||||||
|
#ifndef INSERTION_SORT_H
|
||||||
|
#define INSERTION_SORT_H
|
||||||
|
|
||||||
|
void insertion_sort(int *numbers, const int length);
|
||||||
|
|
||||||
|
#endif
|
@ -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", ¤t_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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user