-
-
Save ReneSac/f3afa585841d72df2d02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| proc sort*[A](t: var TCountTable[A]) = | |
| ## sorts the count table so that the entry with the highest counter comes | |
| ## first. This is destructive! You must not modify `t` afterwards! | |
| ## You can use the iterators `pairs`, `keys`, and `values` to iterate over | |
| ## `t` in the sorted order. | |
| # we use shellsort here; fast enough and simple | |
| var h = 1 | |
| while true: | |
| h = 3 * h + 1 | |
| if h >= high(t.data): break | |
| while true: | |
| h = h div 3 | |
| for i in countup(h, high(t.data)): | |
| var j = i | |
| while t.data[j-h].val <= t.data[j].val: | |
| swap(t.data[j], t.data[j-h]) | |
| j = j-h | |
| if j < h: break | |
| if h == 1: break | |
| proc largest*[A](t: TCountTable[A]): tuple[key: A, val: int] = | |
| ## returns the (key,val)-pair with the largest `val`. Efficiency: O(n) | |
| assert t.len > 0 | |
| var maxIdx = 0 | |
| for h in 1..high(t.data): | |
| if t.data[maxIdx].val < t.data[h].val: maxIdx = h | |
| result.key = t.data[maxIdx].key | |
| result.val = t.data[maxIdx].val |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment