Skip to content

Commit f78a970

Browse files
committed
Avoid a sequence copy then reinsertion after angle sort
1 parent f37621b commit f78a970

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed

contents/graham_scan/code/nim/graham.nim

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from algorithm import sorted
1+
from algorithm import sort, sorted
22
from math import arctan2
33
from sequtils import deduplicate, map, toSeq
44
import sugar
@@ -21,15 +21,12 @@ proc flipped_point_cmp(pa, pb: Point): int =
2121

2222
proc graham_scan(gift: seq[Point]): seq[Point] =
2323
assert(gift.len >= 3)
24-
let
25-
gift_without_duplicates = sorted(deduplicate(gift), flipped_point_cmp)
26-
pivot = gift_without_duplicates[0]
27-
var
28-
points = sorted(gift_without_duplicates[1..^1],
29-
proc (pa, pb: Point): int =
30-
if polar_angle(pivot, pa) < polar_angle(pivot, pb): -1
31-
else: 1)
32-
points.insert(pivot, 0)
24+
var points = sorted(deduplicate(gift), flipped_point_cmp)
25+
let pivot = points[0]
26+
sort(toOpenArray(points, 1, high(points)),
27+
proc (pa, pb: Point): int =
28+
if polar_angle(pivot, pa) < polar_angle(pivot, pb): -1
29+
else: 1)
3330
var
3431
m = 1
3532
en = toSeq(low(points) + 2..high(points))

0 commit comments

Comments
 (0)