Why sort function in Go and C++ is different? And I can't get the right results in Go


I want to sort a slice named nums while not disrupting the original order.
So I use inds to record the index of nums and sort inds:

vector<int> nums = {1,3,2,1,1,1};
vector<int> inds = {0,1,2,3,4,5};
sort(inds.begin(), inds.end(), 
    [nums](int i, int j) -> bool
    return nums[i] > nums[j]; 

for(int i : inds) {
    cout << i;

The inds is 120345 after sort. While in Go, I test:

nums := []int{1,3,2,1,1,1}
inds := []int{0,1,2,3,4,5}

sort.Slice(inds, func(i, j int) bool {
    return nums[i] > nums[j]


And The inds is [1 0 2 3 4 5] after sort, which is different from the result of C++ and what I expected.
Why Go can’t sort inds well?


The anonymous function arguments i and j are indices in inds, but the program uses the arguments as indices in nums.

Fix by using inds to translate the index values to nums:

sort.Slice(inds, func(i, j int) bool {
    return nums[inds[i]] > nums[inds[j]]

Answered By – Zombo

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.