Skip to content

Add a Quicksort implementation. #15380

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/libcollections/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ use vec::Vec;
pub use core::slice::{ref_slice, mut_ref_slice, Splits, Windows};
pub use core::slice::{Chunks, Vector, ImmutableVector, ImmutableEqVector};
pub use core::slice::{ImmutableOrdVector, MutableVector, Items, MutItems};
pub use core::slice::{MutSplits, MutChunks};
pub use core::slice::{MutableOrdVector, MutSplits, MutChunks};
pub use core::slice::{bytes, MutableCloneableVector};

// Functional utilities
Expand Down Expand Up @@ -589,7 +589,7 @@ impl<'a,T> MutableVectorAllocating<'a, T> for &'a mut [T] {

/// Methods for mutable vectors with orderable elements, such as
/// in-place sorting.
pub trait MutableOrdVector<T> {
pub trait MutableOrdVectorAllocating<T> {
/// Sort the vector, in place.
///
/// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
Expand Down Expand Up @@ -635,7 +635,7 @@ pub trait MutableOrdVector<T> {
fn prev_permutation(self) -> bool;
}

impl<'a, T: Ord> MutableOrdVector<T> for &'a mut [T] {
impl<'a, T: Ord> MutableOrdVectorAllocating<T> for &'a mut [T] {
#[inline]
fn sort(self) {
self.sort_by(|a,b| a.cmp(b))
Expand Down
41 changes: 40 additions & 1 deletion src/libcollections/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ use core::ptr;
use core::uint;

use {Collection, Mutable};
use slice::{MutableOrdVector, MutableVectorAllocating, CloneableVector};
use slice::{MutableOrdVector, MutableOrdVectorAllocating};
use slice::{MutableVectorAllocating, CloneableVector};
use slice::{Items, MutItems};

/// An owned, growable vector.
Expand Down Expand Up @@ -805,6 +806,29 @@ impl<T> Vec<T> {
self.as_mut_slice().sort_by(compare)
}

/// Sort the vector, in place, using `compare` to compare elements,
/// using the Quicksort algorithm.
///
/// This sort is `O(n log n)` average-case and does not allocate memory,
/// but is `O(n^2)` worst-case and is *not* stable.
/// See the `sort_by` method for a stable alternative.
///
/// # Example
///
/// ```rust
/// let mut v = vec!(5i, 4, 1, 3, 2);
/// v.quicksort_by(|a, b| a.cmp(b));
/// assert_eq!(v, vec!(1i, 2, 3, 4, 5));
///
/// // reverse sorting
/// v.quicksort_by(|a, b| b.cmp(a));
/// assert_eq!(v, vec!(5i, 4, 3, 2, 1));
/// ```
#[inline]
pub fn quicksort_by(&mut self, compare: |&T, &T| -> Ordering) {
self.as_mut_slice().quicksort_by(compare)
}

/// Returns a slice of self spanning the interval [`start`, `end`).
///
/// # Failure
Expand Down Expand Up @@ -1302,6 +1326,21 @@ impl<T:Ord> Vec<T> {
pub fn sort(&mut self) {
self.as_mut_slice().sort()
}

/// Sort the vector, in place, using the Quicksort algorithm.
///
/// This is equivalent to `self.quicksort_by(|a, b| a.cmp(b))`.
///
/// # Example
///
/// ```rust
/// let mut vec = vec!(3i, 1, 2);
/// vec.quicksort();
/// assert_eq!(vec, vec!(1, 2, 3));
/// ```
pub fn quicksort(&mut self) {
self.as_mut_slice().quicksort()
}
}

impl<T> Mutable for Vec<T> {
Expand Down
128 changes: 128 additions & 0 deletions src/libcore/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,84 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
}
}

// FIXME(SimonSapin): Make `compare` a by-ref closure when that’s supported,
// and remove the return value.
fn quicksort_helper<'a, T>(arr: &mut [T], left: int, right: int,
compare: |&T, &T|: 'a -> Ordering)
-> |&T, &T|: 'a -> Ordering {
if right <= left {
return compare
}

let mut i: int = left - 1;
let mut j: int = right;
let mut p: int = i;
let mut q: int = j;
unsafe {
let v: *mut T = &mut arr[right as uint];
loop {
i += 1;
while compare(&arr[i as uint], &*v) == Less {
i += 1
}
j -= 1;
while compare(&*v, &arr[j as uint]) == Less {
if j == left {
break
}
j -= 1;
}
if i >= j {
break
}
arr.swap(i as uint, j as uint);
if compare(&arr[i as uint], &*v) == Equal {
p += 1;
arr.swap(p as uint, i as uint)
}
if compare(&*v, &arr[j as uint]) == Equal {
q -= 1;
arr.swap(j as uint, q as uint)
}
}
}

arr.swap(i as uint, right as uint);
j = i - 1;
i += 1;
let mut k: int = left;
while k < p {
arr.swap(k as uint, j as uint);
k += 1;
j -= 1;
assert!(k < arr.len() as int);
}
k = right - 1;
while k > q {
arr.swap(i as uint, k as uint);
k -= 1;
i += 1;
assert!(k != 0);
}

let compare = quicksort_helper(arr, left, j, compare);
let compare = quicksort_helper(arr, i, right, compare);
compare
}

/// An in-place quicksort.
///
/// The algorithm is from Sedgewick and Bentley, "Quicksort is Optimal":
/// http://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf
fn quicksort<T>(arr: &mut [T], compare: |&T, &T| -> Ordering) {
if arr.len() <= 1 {
return
}

let len = arr.len();
quicksort_helper(arr, 0, (len - 1) as int, compare);
}

/// Extension methods for vectors such that their elements are
/// mutable.
pub trait MutableVector<'a, T> {
Expand Down Expand Up @@ -534,6 +612,26 @@ pub trait MutableVector<'a, T> {
/// ```
fn reverse(self);

/// Sort the vector, in place, using `compare` to compare elements,
/// using the Quicksort algorithm.
///
/// This sort is `O(n log n)` average-case and does not allocate memory,
/// but is `O(n^2)` worst-case and is *not* stable.
/// See the `sort_by` method for a stable alternative.
///
/// # Example
///
/// ```rust
/// let mut v = [5i, 4, 1, 3, 2];
/// v.quicksort_by(|a, b| a.cmp(b));
/// assert!(v == [1, 2, 3, 4, 5]);
///
/// // reverse sorting
/// v.quicksort_by(|a, b| b.cmp(a));
/// assert!(v == [5, 4, 3, 2, 1]);
/// ```
fn quicksort_by(self, compare: |&T, &T| -> Ordering);

/// Returns an unsafe mutable pointer to the element in index
unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T;

Expand Down Expand Up @@ -711,6 +809,11 @@ impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
}
}

#[inline]
fn quicksort_by(self, compare: |&T, &T| -> Ordering) {
quicksort(self, compare)
}

#[inline]
unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T {
transmute((self.repr().data as *mut T).offset(index as int))
Expand Down Expand Up @@ -739,6 +842,31 @@ impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
}
}

/// Methods for mutable vectors with orderable elements, such as
/// in-place sorting.
pub trait MutableOrdVector<T> {
/// Sort the vector, in place, using the Quicksort algorithm.
///
/// This is equivalent to `self.quicksort_by(|a, b| a.cmp(b))`.
///
/// # Example
///
/// ```rust
/// let mut v = [-5i, 4, 1, -3, 2];
///
/// v.quicksort();
/// assert!(v == [-5i, -3, 1, 2, 4]);
/// ```
fn quicksort(self);
}

impl<'a, T: Ord> MutableOrdVector<T> for &'a mut [T] {
#[inline]
fn quicksort(self) {
self.quicksort_by(|a, b| a.cmp(b))
}
}

/// Extension methods for vectors contain `PartialEq` elements.
pub trait ImmutableEqVector<T:PartialEq> {
/// Find the first index containing a matching value
Expand Down
1 change: 1 addition & 0 deletions src/libcoretest/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ mod option;
mod ptr;
mod raw;
mod result;
mod slice;
mod tuple;
40 changes: 40 additions & 0 deletions src/libcoretest/slice.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::rand::{Rng, task_rng};


#[test]
fn test_quicksort() {
for len in range(4u, 25) {
for _ in range(0i, 100) {
let mut v = task_rng().gen_iter::<uint>().take(len)
.collect::<Vec<uint>>();
let mut v1 = v.clone();

v.as_mut_slice().quicksort();
assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));

v1.as_mut_slice().quicksort_by(|a, b| a.cmp(b));
assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));

v1.as_mut_slice().quicksort_by(|a, b| b.cmp(a));
assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
}
}

// shouldn't fail/crash
let mut v: [uint, .. 0] = [];
v.quicksort();

let mut v = [0xDEADBEEFu];
v.quicksort();
assert!(v == [0xDEADBEEF]);
}
2 changes: 1 addition & 1 deletion src/libstd/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
#[doc(no_inline)] pub use slice::{ImmutableVector, MutableVector};
#[doc(no_inline)] pub use slice::{ImmutableEqVector, ImmutableOrdVector};
#[doc(no_inline)] pub use slice::{Vector, VectorVector};
#[doc(no_inline)] pub use slice::MutableVectorAllocating;
#[doc(no_inline)] pub use slice::{MutableVectorAllocating, MutableOrdVectorAllocating};
#[doc(no_inline)] pub use string::String;
#[doc(no_inline)] pub use vec::Vec;

Expand Down