Skip to content

Add ArrayList.sort #3917

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions lib/std/array_list.zig
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,10 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type {
if (self.len == 0) return null;
return self.pop();
}

pub fn sort(self: *Self, lessThan: fn (lhs: T, rhs: T) bool) void {
std.sort.sort(T, self.items[0..self.len], lessThan);
}
};
}

Expand Down Expand Up @@ -442,3 +446,20 @@ test "std.ArrayList: ArrayList(T) of struct T" {
try root.sub_items.append(Item{ .integer = 42, .sub_items = ArrayList(Item).init(debug.global_allocator) });
testing.expect(root.sub_items.items[0].integer == 42);
}

test "std.ArrayList.sort" {
var list = ArrayList(i32).init(debug.global_allocator);
defer list.deinit();

try list.append(4);
try list.append(2);
try list.append(1);
try list.append(3);

list.sort(std.sort.asc(i32));

testing.expect(list.items[0] == 1);
testing.expect(list.items[1] == 2);
testing.expect(list.items[2] == 3);
testing.expect(list.items[3] == 4);
}