Created
June 18, 2022 00:36
-
-
Save Per48edjes/5615fc31e77b34c48548db5b650e4914 to your computer and use it in GitHub Desktop.
Implementation of insertion sort on array of integers in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
void swap(int *a, int *b); | |
void insert(int *subseq, int subseq_len); | |
void print_array(int *arr, int len_arr); | |
int main(void) | |
{ | |
int items[] = { | |
5, 2, 7, 4, 1, 6, 3, 0 | |
}; | |
int len_items = sizeof(items) / sizeof(*items); | |
// Print original order | |
print_array(items, len_items); | |
// Insertion sort | |
int i = 1; | |
while (i < len_items) { | |
insert(items, i); | |
++i; | |
} | |
// Print sorted order | |
print_array(items, len_items); | |
return EXIT_SUCCESS; | |
} | |
void swap(int *a, int *b) | |
{ | |
int tmp = *a; | |
*a = *b; | |
*b = tmp; | |
} | |
void insert(int *subseq, int subseq_len) | |
{ | |
int i = subseq_len - 1; | |
const int insert_value = subseq[subseq_len]; | |
while (i >= 0 && insert_value < subseq[i]) { | |
swap(&subseq[i], &subseq[i+1]); | |
--i; | |
} | |
} | |
void print_array(int *arr, int len_arr) | |
{ | |
for (int i = 0; i < len_arr; ++i) | |
{ | |
printf("%d ", arr[i]); | |
if (len_arr - 1 == i) | |
{ | |
printf("\n"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment