home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!sun4nl!and!jos
- From: jos@and.nl (Jos Horsmeier)
- Newsgroups: comp.lang.c
- Subject: Re: Sort help needed
- Message-ID: <3223@dozo.and.nl>
- Date: 13 Aug 92 08:32:07 GMT
- References: <1992Aug12.154130.1@ducvax.auburn.edu>
- Organization: AND Software BV Rotterdam
- Lines: 75
-
- In article <1992Aug12.154130.1@ducvax.auburn.edu> swanger@ducvax.auburn.edu writes:
- |I am writing a program in C. I have an array of character strings that
- |I want to sort (I dynamically allocate the "array" with a series of
- |calloc statements, so to the purist I suppose it isn't really an array,
- |I just pretend like it is one). The array usually contains around 1800
- |strings of 512 characters each. I sort the array (sort the pointers
- |actually) with the following sort routine (on a SUN IPC Sparcstation)
- |and it usually takes 8 to 10 seconds to finish. [ and this is too slow ... ]
-
- |------------------------------------------------------------------------
- |void sort_strings(strings, num)
- |char *strings[];
- |int num;
- |{
- [ bubble sort algorithm deleted ... ]
- |}
-
- I strongly suggest _not_ to use this algorithm. It's dead slow, it
- takes up O(n^2) loop iterations to sort the strings. In your example,
- sorting 1800 strings, the innermost instructions (inside both loops)
- are executed n*(n-1)/2= 1619100 times.
-
- Have a look at the qsort function, it's in you lib somewhere. If you can't
- use that function for some reason (I don't see why,) may I suggest an
- alternative algorithm: heap sort. It's a bit slower than quick sort,
- but it's a very stable algorithm. i.e. quicksort might degenerate to
- O(n^2) behavior in the worst case, but heap sort is stable at O(n*log(n)).
- Both algortihms sort the array `in place', they don't need additional
- storage. An rudimentary implementation of the heap sort looks something
- like this:
-
- void heap_sort(strings, num)
- char *strings[];
- int num;
- {
- int n;
-
- for (n= num/2; n >= 0; n--) /* Build the inital heap */
- heapify(strings, n, num);
-
- for (n= 0; n < num; n++) { /* Swap root and last element */
- swap(strings, 0, num-1-n);
- heapify(strings, 0, num-1-n); /* Build new (smaller) heap */
- }
-
- }
-
- void heapify(strings, n, num)
- char *strings[];
- int n; /* Position in the heap */
- int num; /* Number of strings */
- {
- int l, r; /* Left and right sons */
-
- for(; (l= 2*n+1) < num;) { /* Loop while left son present */
- if ((r= l+1) < num) /* Right son present? */
- if (strcmp(strings[l],
- strings[r] < 0) /* Right son > left son */
- l= r;
- if (strcmp(strings[n],
- strings[l]) >= 0) /* Already a heap here */
- break;
-
- swap(strings, n, l); /* Swap root with son */
-
- n= l; /* Descent this sub tree */
- }
-
- }
-
- I hope this is of any help to you,
-
- kind regards,
-
- Jos aka jos@and.nl
-