1 /* tsort - topological sort.
2 Copyright (C) 1998, 1999 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by Mark Kettenis <kettenis@phys.uva.nl>. */
20 /* The topological sort is done according to Algorithm T (Topological
21 sort) in Donald E. Knuth, The Art of Computer Programming, Volume
22 1/Fundamental Algorithms, page 262. */
33 #include "long-options.h"
35 #include "readtokens.h"
37 /* The official name of this program (e.g., no `g' prefix). */
38 #define PROGRAM_NAME "tsort"
40 #define AUTHORS "Mark Kettenis"
42 /* Token delimiters when reading from a file. */
47 /* Members of the list of successors. */
51 struct successor
*next
;
54 /* Each string is held in core as the head of a list of successors. */
58 struct item
*left
, *right
;
62 struct successor
*top
;
65 /* The name this program was run with. */
68 /* Nonzero if any of the input files are the standard input. */
69 static int have_read_stdin
;
71 /* The head of the sorted list. */
72 static struct item
*head
= NULL
;
74 /* The tail of the list of `zeros', strings that have no predecessors. */
75 static struct item
*zeros
= NULL
;
77 /* The number of strings to sort. */
78 static int n_strings
= 0;
80 static struct option
const long_options
[] =
89 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
94 Usage: %s [OPTION] [FILE]\n\
95 Write totally ordered list consistent with the partial ordering in FILE.\n\
96 With no FILE, or when FILE is -, read standard input.\n\
98 --help display this help and exit\n\
99 --version output version information and exit\n"),
101 puts (_("\nReport bugs to <textutils-bugs@gnu.org>."));
104 exit (status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);
107 /* Create a new item/node for STR. */
109 new_item (const char *str
)
111 struct item
*k
= xmalloc (sizeof (struct item
));
113 k
->str
= (str
? xstrdup (str
): NULL
);
114 k
->left
= k
->right
= NULL
;
117 /* T1. Initialize (COUNT[k] <- 0 and TOP[k] <- ^). */
125 /* Search binary tree rooted at *ROOT for STR. Allocate a new tree if
126 *ROOT is NULL. Insert a node/item for STR if not found. Return
127 the node/item found/created for STR.
129 This is done according to Algorithm A (Balanced tree search and
130 insertion) in Donald E. Knuth, The Art of Computer Programming,
131 Volume 3/Searching and Sorting, pages 455--457. */
134 search_item (struct item
*root
, const char *str
)
136 struct item
*p
, *q
, *r
, *s
, *t
;
141 /* Make sure the tree is not empty, since that is what the algorithm
143 if (root
->right
== NULL
)
144 return (root
->right
= new_item (str
));
146 /* A1. Initialize. */
153 a
= strcmp (str
, p
->str
);
157 /* A3 & A4. Move left & right. */
168 /* A3 & A4. (continued). */
174 /* A6. Adjust balance factors. */
175 assert (!STREQ (str
, s
->str
));
176 if (strcmp (str
, s
->str
) < 0)
189 assert (!STREQ (str
, p
->str
));
190 if (strcmp (str
, p
->str
) < 0)
202 /* A7. Balancing act. */
203 if (s
->balance
== 0 || s
->balance
== -a
)
211 /* A8. Single Rotation. */
223 s
->balance
= r
->balance
= 0;
227 /* A9. Double rotation. */
249 else if (p
->balance
== -a
)
254 /* A10. Finishing touch. */
263 /* A3 & A4. (continued). */
276 /* Record the fact that J precedes K. */
279 record_relation (struct item
*j
, struct item
*k
)
283 if (!STREQ (j
->str
, k
->str
))
286 p
= xmalloc (sizeof (struct successor
));
294 count_items (struct item
*k
)
300 scan_zeros (struct item
*k
)
313 /* If K is part of a loop, print the loop on standard error, and exit. */
316 detect_loop (struct item
*k
)
320 while (k
&& k
->count
> 0)
323 fprintf (stderr
, "%s: %s\n", program_name
, k
->str
);
331 /* Recurse (sub)tree rooted at ROOT, calling ACTION for each node. */
334 recurse_tree (struct item
*root
, void (*action
) (struct item
*))
336 if (root
->left
== NULL
&& root
->right
== NULL
)
340 if (root
->left
!= NULL
)
341 recurse_tree (root
->left
, action
);
343 if (root
->right
!= NULL
)
344 recurse_tree (root
->right
, action
);
348 /* Walk the tree specified by the head ROOT, calling ACTION for
352 walk_tree (struct item
*root
, void (*action
) (struct item
*))
355 recurse_tree (root
->right
, action
);
358 /* Do a topological sort on FILE. */
361 tsort (const char *file
)
364 struct item
*j
= NULL
;
365 struct item
*k
= NULL
;
367 token_buffer tokenbuffer
;
369 /* Intialize the head of the tree will hold the strings we're sorting. */
370 root
= new_item (NULL
);
372 if (STREQ (file
, "-"))
379 fp
= fopen (file
, "r");
381 error (EXIT_FAILURE
, errno
, "%s", file
);
384 init_tokenbuffer (&tokenbuffer
);
390 /* T2. Next Relation. */
391 len
= readtoken (fp
, DELIM
, sizeof (DELIM
) - 1, &tokenbuffer
);
397 k
= search_item (root
, tokenbuffer
.buffer
);
400 /* T3. Record the relation. */
401 record_relation (j
, k
);
408 /* T1. Initialize (N <- n). */
409 walk_tree (root
, count_items
);
411 /* T4. Scan for zeros. */
412 walk_tree (root
, scan_zeros
);
416 struct successor
*p
= head
->top
;
418 /* T5. Output front of queue. */
419 printf ("%s\n", head
->str
);
422 /* T6. Erase relations. */
426 if (p
->suc
->count
== 0)
428 zeros
->qlink
= p
->suc
;
435 /* T7. Remove from queue. */
439 /* T8. End of process. */
440 assert (n_strings
>= 0);
443 error (0, 0, _("%s: input contains a loop:\n"),
444 (have_read_stdin
? "-" : file
));
446 /* Print out loop. */
447 walk_tree (root
, detect_loop
);
449 /* Should not happen. */
450 error (EXIT_FAILURE
, 0, _("could not find loop"));
455 main (int argc
, char **argv
)
459 program_name
= argv
[0];
460 setlocale (LC_ALL
, "");
461 bindtextdomain (PACKAGE
, LOCALEDIR
);
462 textdomain (PACKAGE
);
464 parse_long_options (argc
, argv
, PROGRAM_NAME
, GNU_PACKAGE
, VERSION
,
467 while ((opt
= getopt_long (argc
, argv
, "", long_options
, NULL
)) != -1)
470 case 0: /* long option */
473 usage (EXIT_FAILURE
);
478 if (optind
+ 1 < argc
)
480 error (0, 0, _("only one argument may be specified"));
481 usage (EXIT_FAILURE
);
485 tsort (argv
[optind
]);
489 if (fclose (stdout
) == EOF
)
490 error (EXIT_FAILURE
, errno
, _("write error"));
492 if (have_read_stdin
&& fclose (stdin
) == EOF
)
493 error (EXIT_FAILURE
, errno
, _("standard input"));