Help with sort: it does not seem to do anything.

I'm a bit confused, I have a very simple sort example, but it does not do anything at all. I must be doing something wrong, because I cannot image that I'm the first to touch this code. What is going on here? The following code gives as output:
mojo bug1.mojo
before: 0 13 76 46 53 22 4 68 68 94 38 52 83 3 5 53 67 0 38 6 42 69 59 93 85 53 9 66 42 70 91 76
after: 0 13 76 46 53 22 4 68 68 94 38 52 83 3 5 53 67 0 38 6 42 69 59 93 85 53 9 66 42 70 91 76
mojo bug1.mojo
before: 0 13 76 46 53 22 4 68 68 94 38 52 83 3 5 53 67 0 38 6 42 69 59 93 85 53 9 66 42 70 91 76
after: 0 13 76 46 53 22 4 68 68 94 38 52 83 3 5 53 67 0 38 6 42 69 59 93 85 53 9 66 42 70 91 76
code:
from random import random_ui64
from algorithm.sort import sort

fn main():
alias size = 32

var data_vec = DynamicVector[SIMD[DType.uint32, 1]](size)
for i in range(size):
data_vec[i] = random_ui64(0, 100).cast[DType.uint32]()

print_no_newline("before: ")
for i in range(size):
print_no_newline(str(data_vec[i]) + " ")
print("")

sort[DType.uint32](data_vec) # inplace sorting does not seem to work

print_no_newline("after: ")
for i in range(size):
print_no_newline(str(data_vec[i]) + " ")
print("")
from random import random_ui64
from algorithm.sort import sort

fn main():
alias size = 32

var data_vec = DynamicVector[SIMD[DType.uint32, 1]](size)
for i in range(size):
data_vec[i] = random_ui64(0, 100).cast[DType.uint32]()

print_no_newline("before: ")
for i in range(size):
print_no_newline(str(data_vec[i]) + " ")
print("")

sort[DType.uint32](data_vec) # inplace sorting does not seem to work

print_no_newline("after: ")
for i in range(size):
print_no_newline(str(data_vec[i]) + " ")
print("")
4 Replies
Henk-Jan Lebbink
GitHub
[BUG]: Inplace sort seems to do nothing · Issue #1508 · modularml/m...
Bug description A simple sortDType.uint32 (that is: sort[type: DType](inout v: DynamicVector[SIMD[type, 1]])) does not sort the vector. In fact, it doesn't appear to do anything wha...
ModularBot
ModularBot9mo ago
Congrats @Henk-Jan Lebbink, you just advanced to level 2!
Michael K
Michael K9mo ago
var data_vec = DynamicVector[UInt32](size) is not doing what you want. Setting the capacity to 32 allocates an internal pointer but it leaves data_vec.size as 0. You want to use .resize(size, 0) or just add your random numbers with .push_back() .
Henk-Jan Lebbink
@Michael K Thanx for the help. Aha capacity instead of size. __init__(inout self: Self, capacity: Int)
Want results from more Discord servers?
Add your server