Upload files to 'Exercise 4 - BST Sort (Week 5)'

master
Manish 3 years ago
parent cab8a393f7
commit 0e9442b99d

@ -0,0 +1,50 @@
405
130
484
446
336
377
658
853
678
436
709
996
885
758
896
947
255
737
489
430
886
327
877
860
924
8
348
412
158
932
935
229
619
590
373
483
543
888
566
229
959
337
399
724
380
494
477
61
396
642

@ -0,0 +1,87 @@
/* 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);
}

@ -0,0 +1,2 @@
ex4: ex4.c
gcc -std=c11 -Wall ex4.c -o ex4

Binary file not shown.

After

Width:  |  Height:  |  Size: 449 KiB

Loading…
Cancel
Save