DEV Community

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

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
}