Skip to content

Instantly share code, notes, and snippets.

@jamesdavidson
Created January 24, 2015 08:10
Show Gist options
  • Save jamesdavidson/3aeaaadb006c1c7f44d8 to your computer and use it in GitHub Desktop.
Save jamesdavidson/3aeaaadb006c1c7f44d8 to your computer and use it in GitHub Desktop.
A basic tree sort algorithm.
/* A Saturday afternoon hack project.
* Sort integers from stdin using a binary tree.
* This algorithm is O(n^2) in the worst case though!
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int value;
struct node_t * left;
struct node_t * right;
} node_t;
void insert_node(node_t * tree, int value);
node_t * create_node(void);
void destroy_node(node_t * node);
int
main(int argc, char ** argv) {
node_t * root;
char buffer[100];
char * ptr;
root = create_node();
ptr = buffer;
while ((*ptr = getchar()) != EOF) {
if(*ptr=='\n') {
*ptr = '\0';
insert_node(root,atoi(ptr = buffer));
}
else {
ptr++;
}
}
destroy_node(root);
return 0;
}
void
insert_node(node_t * tree, int value) {
node_t * node = tree;
while (node->value != 0) {
node = (value < (node->value)) ?
((node->left != NULL) ? (node->left) : (node->left = create_node())):
((node->right != NULL) ? (node->right) : (node->right = create_node()));
}
node->value = value;
return;
}
node_t *
create_node(void) {
node_t * node = malloc(sizeof(node_t));
node->value = 0, node->left = NULL, node->right = NULL;
return node;
}
void
destroy_node(node_t * node) {
if(node->left != NULL) destroy_node(node->left);
printf("%d\n", node->value);
if(node->right != NULL) destroy_node(node->right);
return free(node);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment