Last active
August 29, 2015 14:16
-
-
Save kanatzidis/5b98e29bdd54a54f1d33 to your computer and use it in GitHub Desktop.
Simple C bubblesort implementation
This file contains 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> | |
#include <string.h> | |
int* bubble(int array[], size_t size); | |
int main(void) | |
{ | |
int i; | |
size_t size; | |
int* sorted; | |
int array[7] = { 3, 9, 4, 6, 2, 8, 5 }; | |
//int array[5] = { 5, 4, 3, 2, 1 }; | |
size = sizeof(array)/sizeof(array[0]); | |
printf("size: %zu\n", size); | |
sorted = bubble(array, size); | |
for(i = 0; i < size; i++) { | |
printf("%d\n", sorted[i]); | |
} | |
free(sorted); | |
return 0; | |
} | |
int* bubble(int array[], size_t size) { | |
int i, tmp, correct = 0; | |
int* sorted = malloc(sizeof(int)*size); | |
memcpy(sorted, array, sizeof(int)*size); | |
while(!correct) { | |
correct = 1; | |
for(i = 0; i < size-1; i++) { | |
if(sorted[i] > sorted[i+1]) { | |
correct = 0; | |
tmp = sorted[i+1]; | |
sorted[i+1] = sorted[i]; | |
sorted[i] = tmp; | |
} | |
} | |
} | |
return sorted; | |
} |
This file contains 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> | |
int bubble(int array[], size_t size); | |
int main(void) | |
{ | |
int i; | |
size_t size; | |
int array[7] = { 3, 9, 4, 6, 2, 8, 5 }; | |
//int array[5] = { 5, 4, 3, 2, 1 }; | |
int runs; | |
size = sizeof(array)/sizeof(array[0]); | |
printf("size: %zu\n", size); | |
runs = bubble(array, size); | |
for(i = 0; i < size; i++) { | |
printf("%d\n", array[i]); | |
} | |
printf("%d runs\n", runs); | |
return 0; | |
} | |
int bubble(int array[], size_t size) { | |
int i, tmp, correct = 0; | |
int runs = 0; | |
while(!correct) { | |
correct = 1; | |
for(i = 0; i < size-1; i++) { | |
runs++; | |
if(array[i] > array[i+1]) { | |
correct = 0; | |
tmp = array[i+1]; | |
array[i+1] = array[i]; | |
array[i] = tmp; | |
} | |
} | |
} | |
return runs; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment