Skip to content
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

package sort do sort.Slice(), The result is not the intended result #39370

Closed
imkos opened this issue Jun 3, 2020 · 3 comments
Closed

package sort do sort.Slice(), The result is not the intended result #39370

imkos opened this issue Jun 3, 2020 · 3 comments

Comments

@imkos
Copy link

@imkos imkos commented Jun 3, 2020

What version of Go are you using (go version)?

golang 1.14.4 & golang 1.13.12

Does this issue reproduce with the latest release?

https://play.golang.org/p/2CDG2pa4OmU

What operating system and processor architecture are you using (go env)?

go env Output

What did you do?

What did you expect to see?

njo: [{"feeType":1001,"transType":0,"transactionAmount":355710},{"feeType":1401,"transType":0,"transactionAmount":2775},{"feeType":1602,"transType":0,"transactionAmount":220000},{"feeType":1802,"transType":0,"transactionAmount":4162},{"feeType":1602,"transType":1,"transactionAmount":10000}]

What did you see instead?

njo: [{"feeType":1001,"transType":0,"transactionAmount":355710},{"feeType":1401,"transType":0,"transactionAmount":2775},{"feeType":1602,"transType":0,"transactionAmount":220000},{"feeType":1602,"transType":1,"transactionAmount":10000},{"feeType":1802,"transType":0,"transactionAmount":4162}]
@davecheney
Copy link
Contributor

@davecheney davecheney commented Jun 3, 2020

Thank you for providing a sample program. I believe you are asking why values with different transaction amounts are not sorted as you expected. If this is the case this is because your sorting algorithm does not take the amount into consideration.

https://play.golang.org/p/zYvtpCb-7b6

If I misunderstood your question, would you please clarify.

@randall77
Copy link
Contributor

@randall77 randall77 commented Jun 3, 2020

Your comparison function is incorrect. It isn't antisymmetric. You must add the middle condition here:

func(i, j int) bool {
		if fbs[i].TransType < fbs[j].TransType {
			return true
		}
		if fbs[i].TransType > fbs[j].TransType {
			return false
		}
		// only if TransType are equal, should you compare FeeType
		if fbs[i].FeeType < fbs[j].FeeType {
			return true
		}
		return false
	}
@imkos
Copy link
Author

@imkos imkos commented Jun 3, 2020

Thanks for the reply, I read the reply from randall77, it is indeed a problem with my code

@imkos imkos closed this Jun 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants
You can’t perform that action at this time.