Rust Reference ยท Collections
Rust slice swap, reverse and rotate
Reference for rearranging slices in Rust: swap, swap_with_slice, reverse, rotate_left, rotate_right, select_nth_unstable with panics and complexity.
These methods reorder the elements of a slice in place, without allocating. swap(a, b) exchanges two positions. reverse() flips the whole slice. rotate_left(k) and rotate_right(k) shift elements circularly, moving the ones that fall off one end around to the other.
They are defined on [T], so they work on arrays and vectors, and on sub-slices such as v[2..5].reverse(). None of them needs T: Clone or T: Copy, because elements are moved, never duplicated.
let mut v = [1, 2, 3, 4, 5]; v.swap(0, 4); // [5, 2, 3, 4, 1] v.rotate_left(2); // [3, 4, 1, 5, 2]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> [T] { pub fn swap(&mut self, a: usize, b: usize); pub fn swap_with_slice(&mut self, other: &mut [T]); pub fn reverse(&mut self); pub fn rotate_left(&mut self, mid: usize); pub fn rotate_right(&mut self, k: usize); }
| Name | Description |
|---|---|
a, b |
Indexes of the two elements to exchange. They may be equal (a no-op). |
other |
Another mutable slice of the same length. |
mid |
For rotate_left, the element that becomes first. mid elements move from the front to the back. |
k |
For rotate_right, how many elements move from the back to the front. |
Returns: nothing.
Panics: swap panics if either index is out of bounds. swap_with_slice panics when the lengths differ. rotate_left(mid) panics if mid > len, and rotate_right(k) panics if k > len.
Usage notes
- Cost:
swapis O(1).reverseandrotate_*are O(n) with O(1) extra space. - Rotation is how you move an element within a slice without clones: rotate the range between the old and new position. This is also the idea behind insertion sort steps.
rotate_left(k)equalsrotate_right(len - k). Rotating bylenleaves the slice unchanged.- Swapping vector elements through two indexes:
v.swap(i, j)is the borrow-checker-friendly form. Writinglet t = v[i]; v[i] = v[j]; ...fails for non-Copytypes and needs more code even for numbers. - Two slices of one vector: use
split_at_mutto get two disjoint&mut [T], then callswap_with_sliceorstd::mem::swapon elements. - For a single pair of variables, use
std::mem::swap(&mut a, &mut b). - Reversing an iteration does not need
reverse:.iter().rev()reads backwards without moving anything. - Selecting without a full sort:
select_nth_unstable(n)places the n-th smallest element at indexnin O(n) average time (everything before is smaller or equal), which is handy for medians.