88 lines
1.6 KiB
C
88 lines
1.6 KiB
C
|
/* License: AGPLv3 or later. https://www.gnu.org/licenses/licenses.html
|
||
|
*
|
||
|
* Exercise 4 - BST Sort (Week 5)
|
||
|
* Name: Manish
|
||
|
* Student Login: *****
|
||
|
*
|
||
|
* Compile as:
|
||
|
* $ gcc -std=c11 -Wall -o ex4 ex4.c
|
||
|
*/
|
||
|
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
|
||
|
typedef struct
|
||
|
{
|
||
|
int value;
|
||
|
int left;
|
||
|
int right;
|
||
|
} node;
|
||
|
|
||
|
int insert(int value, int node);
|
||
|
void print();
|
||
|
|
||
|
node array[100];
|
||
|
int root = -1;
|
||
|
int size = 0;
|
||
|
int printed = 0;
|
||
|
|
||
|
int main(void)
|
||
|
{
|
||
|
printf("Enter file name: ");
|
||
|
char filename[257];
|
||
|
// Assuming filename/file path won't be longer than 256 characters
|
||
|
scanf("%256s", filename);
|
||
|
|
||
|
FILE* file = fopen(filename, "r");
|
||
|
if (!file)
|
||
|
{
|
||
|
perror(filename);
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
int n;
|
||
|
while (fscanf(file, " %d ", &n) != EOF && size < 100)
|
||
|
{
|
||
|
root = insert(n, root);
|
||
|
}
|
||
|
|
||
|
print(root);
|
||
|
|
||
|
/* print() will print newline after every 10 numbers printed.
|
||
|
* This will print newline if needed in the end.
|
||
|
*/
|
||
|
if (printed % 10 != 0)
|
||
|
printf("\n");
|
||
|
|
||
|
fclose(file);
|
||
|
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
int insert(int value, int node)
|
||
|
{
|
||
|
if (node < 0)
|
||
|
{
|
||
|
array[size].value = value;
|
||
|
array[size].left = -1;
|
||
|
array[size].right = -1;
|
||
|
return size++;
|
||
|
}
|
||
|
if (value <= array[node].value)
|
||
|
array[node].left = insert(value, array[node].left);
|
||
|
else
|
||
|
array[node].right = insert(value, array[node].right);
|
||
|
return node;
|
||
|
}
|
||
|
|
||
|
void print(int node)
|
||
|
{
|
||
|
if (node < 0)
|
||
|
return;
|
||
|
print(array[node].left);
|
||
|
printf("% 5d", array[node].value);
|
||
|
if (++printed % 10 == 0)
|
||
|
printf("\n");
|
||
|
print(array[node].right);
|
||
|
}
|