1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/**************************************************************************************************
* Copyright 2017 Eric Shimizu Karbstein
* All rights reserved.
*
* This Source Code Form is subject to the terms of the BSD 3-Clause License.
**************************************************************************************************/

//! A module for using sorting algorithms.
//!
//! It contains all major sorting algorithms.

use std::cmp::*;
use rand::prelude::*;

/// Selection Sort: Sort a slice according to the way you define the cmp parameter.
///
/// |           | Time complexity | Space complexity |
/// |:----------|:---------------:|:----------------:|
/// | Best:     | Ω(n^2)          |                  |
/// | Avrg:     | θ(n^2)          |                  |
/// | Worst:    | O(n^2)          | O(1)             |
///
/// #Examples
/// ```rust
/// use algos::sort;
///
/// let mut v = [9, 3, 5, 7, 8, 7];
/// // Crescent sorting
/// sort::selection(&mut v, &|a,b| a<b);
/// ```
pub fn selection<T: Ord, C: Fn(&T, &T) -> bool>(a: &mut [T], cmp: &C) {
    for i in 0..=a.len() {
        let mut i_min = i;
        for j in i+1..a.len() {
            if cmp(&a[j],&a[i_min]) {
                i_min = j;
            }
        }
        if i_min!=i {
            a.swap(i_min, i);
        }
    }
}

/// Bubble Sort: Sort a slice according to the way you define the cmp parameter.
///
/// |           | Time complexity | Space complexity |
/// |:----------|:---------------:|:----------------:|
/// | Best:     | Ω(n)            |                  |
/// | Avrg:     | θ(n^2)          |                  |
/// | Worst:    | O(n^2)          | O(1)             |
///
/// #Examples
/// ```rust
/// use algos::sort;
///
/// let mut v = [9, 3, 5, 7, 8, 7];
/// // Crescent sorting
/// sort::bubble(&mut v, &|a,b| a<b);
/// ```
pub fn bubble<T: Ord, C: Fn(&T, &T) -> bool>(a: &mut [T], cmp: &C) {
    for i in (0..a.len()).rev() {
        for j in 0..i {
            if cmp(&a[j+1],&a[j]) {
                a.swap(j,j+1);
            }
        }
    }
}

/// Cocktail Sort: Sort a slice according to the way you define the cmp parameter.
/// It's a variation of Bubble Sort.
///
/// |           | Time complexity | Space complexity |
/// |:----------|:---------------:|:----------------:|
/// | Best:     | Ω(n)            |                  |
/// | Avrg:     | θ(n^2)          |                  |
/// | Worst:    | O(n^2)          | O(1)             |
///
/// #Examples
/// ```rust
/// use algos::sort;
///
/// let mut v = [9, 3, 5, 7, 8, 7];
/// // Crescent sorting
/// sort::cocktail(&mut v, &|a,b| a<b);
/// ```
pub fn cocktail<T: Ord, C: Fn(&T, &T) -> bool>(a: &mut [T], cmp: &C) {
    let mut changed: bool = true;
    let mut start = 0;
    let mut end = a.len()-1;
    while changed {
        changed = false;
        for i in start..end {
            if cmp(&a[i+1],&a[i]) {
                a.swap(i, i+1);
                changed = true;
            }
        }
        end -= 1;

        if !changed {
            break;
        }

        changed = true;
        for i in (start..end-1).rev() {
            if cmp(&a[i+1],&a[i]) {
                a.swap(i, i+1);
                changed = true;
            }
        }
        start += 1;
    }
}

/// Insection Sort: Sort a slice according to the way you define the cmp parameter.
///
/// |           | Time complexity | Space complexity |
/// |:----------|:---------------:|:----------------:|
/// | Best:     | Ω(n)            |                  |
/// | Avrg:     | θ(n^2)          |                  |
/// | Worst:    | O(n^2)          | O(1)             |
///
/// #Examples
/// ```rust
/// use algos::sort;
///
/// let mut v = [9, 3, 5, 7, 8, 7];
/// // Crescent sorting
/// sort::insection(&mut v, &|a,b| a<b);
/// ```
pub fn insection<T: Ord, C: Fn(&T, &T) -> bool>(a: &mut [T], cmp: &C) {
    for i in 1..a.len() {
        for j in (0..i).rev() {
            if cmp(&a[j+1],&a[j]) {
                a.swap(j, j+1);
            }
        }
    }
}

/// Merge Sort: Sort a slice according to the way you define the cmp parameter.
///
/// |           | Time complexity | Space complexity |
/// |:----------|:---------------:|:----------------:|
/// | Best:     | Ω(nlog(n))      |                  |
/// | Avrg:     | θ(nlog(n))      |                  |
/// | Worst:    | O(nlog(n))      | O(n)             |
///
/// #Examples
/// ```rust
/// use algos::sort;
///
/// let mut v = [9, 3, 5, 7, 8, 7];
/// // Crescent sorting
/// sort::merge(&mut v, &|a,b| a<b);
/// ```
pub fn merge<T: Copy + Ord, C: Fn(&T, &T) -> bool>(a: &mut [T], cmp: &C) {
    let (start, mid, end) = (0, a.len()/2, a.len());
    if end<=1 {
        return;
    }
    merge(&mut a[start..mid], cmp);
    merge(&mut a[mid..end], cmp);
    // Copy array "a" to auxiliar array "o"
    let mut o: Vec<T> = a.to_vec();
    combine(&a[start..mid], &a[mid..end], &mut o[..], cmp);
    // Copy itens of "o" into "a"
    a.copy_from_slice(&o);
}
fn combine<T: Copy + PartialOrd, C: Fn(&T, &T) -> bool>(l: &[T], r: &[T], o: &mut [T], cmp: &C) {
    assert_eq!(r.len()+l.len(), o.len());
    let (mut i, mut j, mut k) = (0, 0, 0);
    while i<l.len() && j<r.len() {
        if cmp(&l[i],&r[j]) {
            o[k] = l[i];
            k += 1;
            i += 1;
        }
        else {
            o[k] = r[j];
            k += 1;
            j += 1;
        }
    }
    if i<l.len() {
        o[k..].copy_from_slice(&l[i..]);
    }
    if j<r.len() {
        o[k..].copy_from_slice(&r[j..]);
    }
}


/// Quick Sort: Sort a slice according to the way you define the cmp parameter.
///
/// |           | Time complexity | Space complexity |
/// |:----------|:---------------:|:----------------:|
/// | Best:     | Ω(nlog(n))      |                  |
/// | Avrg:     | θ(nlog(n))      |                  |
/// | Worst:    | O(n^2)          | O(log(n))        |
///
/// #Examples
/// ```rust
/// use algos::sort;
///
/// let mut v = [9, 3, 5, 7, 8, 7];
/// // Crescent sorting
/// sort::quick(&mut v, &|a,b| a<b);
/// ```
pub fn quick<T: Copy+Ord, C: Fn(&T, &T) -> bool>(a: &mut [T], cmp: &C) {
    let (start, end) = (0, a.len());
    if end<=1 {
        return;
    }
    let mid = partition(a, cmp);
    quick(&mut a[start..mid-1], cmp);
    quick(&mut a[mid..end], cmp);
}
fn partition<T: Copy+Ord, C: Fn(&T, &T) -> bool>(a: &mut [T], cmp: &C) -> usize {
    let (start, end) = (0, a.len()-1);
    // We randomize the choice of the pivot so we have less probability to have Worst case.
    // Then we swap the random element to the end of the array.
    let rand = thread_rng().gen_range(start, end);
    let pivot = a[rand];
    a.swap(rand, end);

    let mut i = start;
    for j in start..end {
        if cmp(&a[j],&pivot) {
            a.swap(i, j);
            i += 1;
        }
    }
    a.swap(i, end);
    i+1
}

///Heap Sort: Sort a slice according to the way you define the cmp parameter.
///
/// |           | Time complexity | Space complexity |
/// |:----------|:---------------:|:----------------:|
/// | Best:     | Ω(nlog(n))      |                  |
/// | Avrg:     | θ(nlog(n))      |                  |
/// | Worst:    | O(nlog(n))      | O(1)             |
///
/// #Examples
/// ```rust
/// use algos::sort;
///
/// let mut v = [9, 3, 5, 7, 8, 7];
/// // Crescent sorting
/// sort::heap(&mut v, &|a,b| a<b);
/// ```
pub fn heap<T: Copy+Ord, C: Fn(&T, &T) -> bool>(a: &mut [T], cmp: &C) {
    let (start, end) = (0, a.len());
    for i in (start..end/2).rev() {
        heapify(&mut a[..], cmp, i);
    }
    for i in (0..end).rev() {
        a.swap(0, i);
        heapify(&mut a[..i], cmp, 0);
    }
}
fn heapify<T: Copy+Ord, C: Fn(&T, &T) -> bool>(a: &mut [T], cmp: &C, aux: usize) {
    let end = a.len();
    let mut root = aux;
    let (left_child, right_child) = (2*aux, 2*aux+1);
    if left_child < end && cmp(&a[root], &a[left_child]) {
        root = left_child;
    }
    if right_child < end && cmp(&a[root], &a[right_child]) {
        root = right_child;
    }
    if root != aux {
        a.swap(aux, root);
        heapify(a, cmp, root);
    }
}


#[cfg(test)]
pub mod test {
    use sort::*;

    #[test]
    pub fn selection_test() {
        let p = [3, 5, 7, 7, 8, 9, 12, 15, 23, 30, 99];
        let mut v = [9, 3, 5, 7, 8, 7, 99, 30, 23, 15, 12];

        selection(&mut v, &|a,b| a<b);
        assert_eq!(v, p);
    }
    #[test]
    pub fn bubble_test() {
        let p = [3, 5, 7, 7, 8, 9, 12, 15, 23, 30, 99];
        let mut v = [9, 3, 5, 7, 8, 7, 99, 30, 23, 15, 12];

        bubble(&mut v, &|a,b| a<b);
        assert_eq!(v, p);
    }
    #[test]
    pub fn cocktail_test() {
        let p = [3, 5, 7, 7, 8, 9, 12, 15, 23, 30, 99];
        let mut v = [9, 3, 5, 7, 8, 7, 99, 30, 23, 15, 12];

        cocktail(&mut v, &|a,b| a<b);
        assert_eq!(v, p);
    }
    #[test]
    pub fn insection_test() {
        let p = [3, 5, 7, 7, 8, 9, 12, 15, 23, 30, 99];
        let mut v = [9, 3, 5, 7, 8, 7, 99, 30, 23, 15, 12];

        insection(&mut v, &|a,b| a<b);
        assert_eq!(v, p);
    }
    #[test]
    pub fn merge_test() {
        let p = [3, 5, 7, 7, 8, 9, 12, 15, 23, 30, 99];
        let mut v = [9, 3, 5, 7, 8, 7, 99, 30, 23, 15, 12];

        merge(&mut v, &|a,b| a<b);
        assert_eq!(v, p);
    }
    #[test]
    pub fn quick_test() {
        let p = [3, 5, 7, 7, 8, 9, 12, 15, 23, 30, 99];
        let mut v = [9, 3, 5, 7, 8, 7, 99, 30, 23, 15, 12];

        quick(&mut v, &|a,b| a<b);
        assert_eq!(v, p);
    }
    #[test]
    pub fn heap_test() {
        let p = [3, 5, 7, 7, 8, 9, 12, 15, 23, 30, 99];
        let mut v = [9, 3, 5, 7, 8, 7, 99, 30, 23, 15, 12];

        heap(&mut v, &|a,b| a<b);
        assert_eq!(v, p);
    }
}