DEV Community

Discussion on: How can you swap two variables without using a third?

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
chinmayj93 profile image
Chinmay Joshi

If that's the case, then why swap at all?

Thread Thread
 
dean profile image
dean

Sorting functions. So you can write something simple like

// at this point in the sort, we know we must
// swap x with some other value
if a[x] < a[y] {
     swap(&a[x], &a[y])
} else {
     swap(&a[x], &a[z]) // a[x] and a[z] may be the same value
}
Collapse
 
theoutlander profile image
Nick Karnik

Can you please elaborate on that?