Skip to content

Commit

Permalink
add array sort function
Browse files Browse the repository at this point in the history
  • Loading branch information
eWert-Online committed Aug 16, 2023
1 parent 26566b0 commit 64cb953
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
32 changes: 32 additions & 0 deletions lib/pinc_includes/stdlib/Base__Array.pi
Original file line number Diff line number Diff line change
Expand Up @@ -180,4 +180,36 @@ library Base__Array {
let nth = fn (array, index) -> {
array[index]
}

let sort = fn (array, f) -> {
let merge = fn (a, b) -> {
let len_a = Base.Array.length(a);
if len_a == 0 {
b
} else {
let len_b = Base.Array.length(b);
if len_b == 0 {
a
} else {
let first_a = a[0];
let first_b = b[0];
if f(first_a, first_b) < 0 {
[first_a] @@ merge(Base.Array.slice(a, 1, len_a), b)
} else {
[first_b] @@ merge(a, Base.Array.slice(b, 1, len_b))
}
}
}
}

let len = Base.Array.length(array);
if len < 2 {
array
} else {
let h = Base.Math.ceil(len / 2);
let first_half = array |> Base.Array.slice(0, h);
let second_half = array |> Base.Array.slice(h, len);
merge(sort(first_half, f), sort(second_half, f));
}
}
}
2 changes: 2 additions & 0 deletions test/array.t/data.pi
Original file line number Diff line number Diff line change
Expand Up @@ -73,5 +73,7 @@ component C {
|> Array.map(fn chunk -> Array.join(chunk, ","))
|> Array.map(fn item -> <div> {item} </div>)
}

{[5, 1, 2, 3, 6, 3, 4, 7] |> Array.sort(fn (a, b) -> a - b)}
</section>
}
9 changes: 9 additions & 0 deletions test/array.t/run.t
Original file line number Diff line number Diff line change
Expand Up @@ -95,5 +95,14 @@
<div> 4,5,6 </div>
<div> 7,8,9 </div>
<div> 10 </div>

1
2
3
3
4
5
6
7
</section>

0 comments on commit 64cb953

Please sign in to comment.