Browse Source

add sort_by_indices overload and test

Phil 3 years ago
parent
commit
63eec25044
2 changed files with 27 additions and 1 deletions
  1. 11 1
      core/slice/sort.odin
  2. 16 0
      tests/core/slice/test_core_slice.odin

+ 11 - 1
core/slice/sort.odin

@@ -39,7 +39,9 @@ sort :: proc(data: $T/[]$E) where ORD(E) {
 }
 }
 
 
 
 
-sort_by_indices :: proc(data: $T/[]$E, indices: []int, allocator := context.allocator) -> (sorted: T) {
+sort_by_indices :: proc{ sort_by_indices_allocate, _sort_by_indices}
+
+sort_by_indices_allocate :: proc(data: $T/[]$E, indices: []int, allocator := context.allocator) -> (sorted: T) {
 	assert(len(data) == len(indices))
 	assert(len(data) == len(indices))
 	sorted = make([]int, len(data), allocator)
 	sorted = make([]int, len(data), allocator)
 	for v, i in indices {
 	for v, i in indices {
@@ -48,6 +50,14 @@ sort_by_indices :: proc(data: $T/[]$E, indices: []int, allocator := context.allo
 	return
 	return
 }
 }
 
 
+_sort_by_indices :: proc(data, sorted: $T/[]$E, indices: []int) {
+	assert(len(data) == len(indices))
+	assert(len(data) == len(sorted))
+	for v, i in indices {
+		sorted[i] = data[v]
+	}
+}
+
 sort_by_indices_overwrite :: proc(data: $T/[]$E, indices: []int) {
 sort_by_indices_overwrite :: proc(data: $T/[]$E, indices: []int) {
 	assert(len(data) == len(indices))
 	assert(len(data) == len(indices))
 	temp := make([]int, len(data), context.allocator)
 	temp := make([]int, len(data), context.allocator)

+ 16 - 0
tests/core/slice/test_core_slice.odin

@@ -155,5 +155,21 @@ test_sort_by_indices :: proc(t: ^testing.T) {
 				}
 				}
 			}
 			}
 		}
 		}
+		{
+			indices := make([]int, test_size)
+			swap := make([]int, test_size)
+			for _, i in indices {
+				indices[i] = i
+			}
+
+			slice.sort_by_indices(indices, swap, f_idx)
+			for v, i in swap {
+				idx_pass := v == f_idx[i]
+				expect(t, idx_pass, "Expected the sorted index to be the same as the result from sort_with_indices")
+				if !idx_pass {
+					break
+				}
+			}
+		}
 	}
 	}
 }
 }