From 82d3973ade5c4f7751bfea02c2e0eba155fc3a17 Mon Sep 17 00:00:00 2001 From: ergz Date: Mon, 7 Aug 2023 23:25:17 -0700 Subject: [PATCH] implements insertion sort in c and pytyhon --- c/insertion-sort.c | 31 +++++++++++++++++++++++++++++++ c/selection-sort.c | 26 ++++++++++++-------------- python/insertion-sort.py | 13 +++++++++++++ 3 files changed, 56 insertions(+), 14 deletions(-) create mode 100644 c/insertion-sort.c create mode 100644 python/insertion-sort.py diff --git a/c/insertion-sort.c b/c/insertion-sort.c new file mode 100644 index 0000000..7eab1a2 --- /dev/null +++ b/c/insertion-sort.c @@ -0,0 +1,31 @@ +#include + +void insertion_sort(int arr[], int len) { + int temp; + int j; + for (int i = 1; i < len; i++) { + temp = arr[i]; + j = i - 1; + while (j >= 0) { + if (temp < arr[j]) { + arr[j + 1] = arr[j]; + } + j--; + } + arr[j + 1] = temp; + } +} + +void print_array(int arr[], int len) { + printf("[ "); + for (int i = 0; i < len; i++) { + printf("%d ", arr[i]); + } + printf("]\n"); +} + +int main() { + int arr[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; + insertion_sort(arr, 10); + print_array(arr, 10); +} \ No newline at end of file diff --git a/c/selection-sort.c b/c/selection-sort.c index 728a1a7..8b3d936 100644 --- a/c/selection-sort.c +++ b/c/selection-sort.c @@ -7,18 +7,16 @@ void swap(int *a, int *b) { } void selection_sort(int arr[], int len) { - int curr_low; - int low_index = 0; - int pass_index = 0; - - for (int i = 0; i < len; i++) { - low_index = i; - for (int j = i + 1; j < len; j++) { - if (arr[i] > arr[j]) { // if we encounter a new low - low_index = j; + int lo_index; + for (int i = 0; i < len; i++) { // keep track of pass + lo_index = i; // low index always starts as the pass iteration + for (int j = i + 1; j < len; j++) { // keep track of array comparisons + if (arr[j] < arr[i]) { + lo_index = j; } - } - swap(&arr[i], &arr[low_index]); + } // after done with this loop we swap the value at lo_index to the current pass index + + swap(&arr[i], &arr[lo_index]); } } @@ -31,7 +29,7 @@ void print_array(int arr[], int len) { } int main() { - int arr[6] = {5, 3, 4, 2, 1, 7}; - selection_sort(arr, 6); - print_array(arr, 6); + int arr[5] = {5, 4, 3, 2, 1}; + selection_sort(arr, 5); + print_array(arr, 5); } \ No newline at end of file diff --git a/python/insertion-sort.py b/python/insertion-sort.py new file mode 100644 index 0000000..80e124b --- /dev/null +++ b/python/insertion-sort.py @@ -0,0 +1,13 @@ +def insertion_sort(array): + for index in range(1, len(array)): + temp_value = array[index] + position = index - 1 + + while position >= 0: + if array[position] > temp_value: + array[position + 1] = array[position] + else: + break + array[position + 1] = temp_value + + return array