Skip to content

Instantly share code, notes, and snippets.

@44100hertz
Last active April 9, 2017 19:09
Show Gist options
  • Save 44100hertz/05e5db1ff561c2d8f37762fb3ed6754f to your computer and use it in GitHub Desktop.
Save 44100hertz/05e5db1ff561c2d8f37762fb3ed6754f to your computer and use it in GitHub Desktop.
C bubble sort exercise
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int bubble_sort(int* nums, int count)
{
int sorted = 0;
int swaps = 0;
while(!sorted) {
sorted = 1;
for(int i=0; i<count; ++i) {
if (nums[i] < nums[i+1]) {
swap(&nums[i], &nums[i+1]);
swaps++;
sorted = 0;
}
}
}
return swaps;
}
int main()
{
clock_t before, after;
int count = 1024;
int ms;
while(1) {
int* nums = malloc(count * sizeof(int));
for(int i=0; i<count; ++i) {
nums[i] = rand();
}
before = clock();
int swaps = bubble_sort(nums, count);
free(nums);
after = clock();
ms = ((after - before) * 1000 / CLOCKS_PER_SEC);
int predicted = (count*count) / 4;
printf("%6d sorted in %5d ms using %8d swaps. Predicted: %d\n",
count, ms, swaps, predicted);
count += 1024;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment