See Also:
C Program To Perform Insertion Sort
C Program To Perform Shell Sort
C Program To Perform Bubble Sort
C Program To Perform Quick Sort
C Program To Perform Radix Sort
C Program To Perform Selection Sort
C Program To Perform Heap Sort
C Program To Perform Merge Sort
C Program To Perform External Sorting
C Program To Perform Sorting Using Binary Search Tree
Example Program To Perform Sorting Using Binary Search Tree(in C):
C Program To Perform Insertion Sort
C Program To Perform Shell Sort
C Program To Perform Bubble Sort
C Program To Perform Quick Sort
C Program To Perform Radix Sort
C Program To Perform Selection Sort
C Program To Perform Heap Sort
C Program To Perform Merge Sort
C Program To Perform External Sorting
C Program To Perform Sorting Using Binary Search Tree
Example Program To Perform Sorting Using Binary Search Tree(in C):
#include <stdlib.h>
struct bstNode {
int value;
struct bstNode *leftptr, *rightptr;
};
struct bstNode *root = NULL;
/* create New newnode */
struct bstNode* createNode(int value) {
struct bstNode *newnode;
newnode = (struct bstNode *)malloc(sizeof (struct bstNode));
newnode->value = value;
newnode->leftptr = newnode->rightptr = NULL;
return newnode;
}
/* bstInsertion new node into the binary search tree */
void bstInsertion(struct bstNode **myNode, int value) {
if (*myNode == NULL) {
*myNode = createNode(value);
} else if (value < (*myNode)->value) {
/* value less than parent - insert left */
bstInsertion(&(*myNode)->leftptr, value);
} else if (value > (*myNode)->value) {
/* value greater than parent - insert right */
bstInsertion(&(*myNode)->rightptr, value);
}
}
/* sorting in binary search tree */
void bstSorting(struct bstNode *myNode) {
if (myNode) {
bstSorting(myNode->leftptr);
printf("%d ", myNode->value);
bstSorting(myNode->rightptr);
}
return;
}
int main(int argc, char *argv[]) {
int value, ch;
FILE *fp;
fp = fopen(argv[1], "r");
if (!fp) {
printf("Unable to open the input file %s\n", argv[1]);
exit(0);
}
printf("Input Data :");
/* Read data from the input file */
while (fscanf(fp, "%d", &value) != EOF) {
bstInsertion(&root, value);
printf("%d ", value);
}
printf("\nSorted Data:");
bstSorting(root);
printf("\n\n");
return 0;
}
Output: (Sorting - Binary Search Tree - C Program)
jp@jp-VirtualBox:~/$ ./a.out input1.txt
Input Data :100 50 75 25 85 45 35 65 15 95 5
Sorted Data:5 15 25 35 45 50 65 75 85 95 100
Input Data :100 50 75 25 85 45 35 65 15 95 5
Sorted Data:5 15 25 35 45 50 65 75 85 95 100
No comments:
Post a Comment