Skip to content

Instantly share code, notes, and snippets.

@JellyWX
Last active March 28, 2019 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JellyWX/d13ead118db8adbc0e737621b529c630 to your computer and use it in GitHub Desktop.
Save JellyWX/d13ead118db8adbc0e737621b529c630 to your computer and use it in GitHub Desktop.
#include "bubble_sort.h"
void bubble_sort(int *array, int buffer_len)
{
bool sorted = true;
for (int i = 0; i < buffer_len; ++i)
{
sorted = true;
for (int j = 0; j < buffer_len - i - 1; ++j)
{
if (array[j] > array[j+1])
{
sorted = false;
swap_elements(array, j, 1);
}
}
if (sorted)
break;
}
}
void swap_elements(int *array, int position, int displacement)
{
int hold_element = array[position + displacement];
array[position + displacement] = array[position];
array[position] = hold_element;
}
void insertion_sort(int *array, int buffer_len)
{
for (int i = 1; i < buffer_len; ++i)
{
int checking_element = array[i];
for (int k = i; k > 0; --k)
{
if (array[k - 1] >= checking_element)
{
array[k] = checking_element;
break;
}
else
{
array[k] = array[k - 1];
}
}
}
}
void print_array(int *array, int array_len)
{
for (int i = 0; i < array_len; ++i)
{
printf("%i, ", array[i]);
}
printf("\n");
}
int main()
{
clock_t t = clock();
int array[] = {8, 2, 5, 0, 4, 5, 1, 1, 6, 4, 6, 5, 8, 4, 0, 9, 8, 2, 5, 0, 4, 5, 1, 1, 6, 4, 6, 5, 8, 4, 0, 9, 8, 2, 5, 0, 4, 5, 1, 1, 6, 4, 6, 5, 8, 4, 0, 9, 8, 2, 5, 0, 4, 5, 1, 1, 6, 4, 6, 5, 8, 4, 0, 9, 8, 2, 5, 0, 4, 5, 1, 1, 6, 4, 6, 5, 8, 4, 0, 9, 8, 2, 5, 0, 4, 5, 1, 1, 6, 4, 6, 5, 8, 4, 0, 9};
int array_len = sizeof(array) / sizeof(array[0]);
//print_array(array, array_len);
//bubble_sort(array, array_len);
insertion_sort(array, array_len);
//print_array(array, array_len);
t = clock() - t;
printf("%ld clicks (%f seconds)\n", t, ((float)t)/CLOCKS_PER_SEC);
}
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
void swap_elements(int *array, int position, int displacement);
void bubble_sort(int *array, int buffer_len);
void insertion_sort(int *array, int buffer_len);
void print_array(int *array, int array_len);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment