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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! Provides fast min and max functionality for collections.
//!
//! ```
//! let mut v = [-5, 4, 1, -3, 2];
//! let max = out::slice::max(&mut v, 3);
//! assert_eq!(max, [1, 2, 4]);
//! ```
//!
//! This library can provide significant performance increase compared to sorting or
//! converting to a heap when `n` is small compared to the length of the slice or iterator.
//!
//! # Benchmarks
//!
//! *n = 100, len = 1_000_000:*
//!
//! ```text
//! openSUSE Tumbleweed, i7-5820K @ 3.30GHz, and 16GiB RAM:
//!
//! test iter::max                 ... bench:     918,253 ns/iter (+/- 99,863)
//! test iter::max_unstable        ... bench:     916,908 ns/iter (+/- 58,050)
//! test slice::max                ... bench:     698,643 ns/iter (+/- 46,373)
//! test slice::max_by_cached_key  ... bench:   1,516,099 ns/iter (+/- 37,853)
//! test slice::max_unstable       ... bench:     655,286 ns/iter (+/- 25,017)
//! test std::binary_heap          ... bench:   6,592,801 ns/iter (+/- 780,590)
//! test std::sort                 ... bench:  63,192,028 ns/iter (+/- 2,338,506)
//! test std::sort_by_cached_key   ... bench:  66,058,834 ns/iter (+/- 5,447,387)
//! test std::sort_unstable        ... bench:  30,953,024 ns/iter (+/- 1,141,696)
//! ```
//!
//! ```text
//! Windows 10 (msvc), i7-5820K @ 3.30GHz, and 16GiB RAM:
//!
//! test iter::max                 ... bench:   2,650,615 ns/iter (+/- 1,427,458)
//! test iter::max_unstable        ... bench:   2,604,860 ns/iter (+/- 1,001,639)
//! test slice::max                ... bench:   2,353,487 ns/iter (+/- 1,140,791)
//! test slice::max_by_cached_key  ... bench:   3,317,930 ns/iter (+/- 1,115,283)
//! test slice::max_unstable       ... bench:   2,221,975 ns/iter (+/- 1,232,170)
//! test std::binary_heap          ... bench:   8,666,095 ns/iter (+/- 3,790,987)
//! test std::sort                 ... bench:  73,953,630 ns/iter (+/- 23,036,689)
//! test std::sort_by_cached_key   ... bench:  79,681,540 ns/iter (+/- 24,554,555)
//! test std::sort_unstable        ... bench:  35,327,180 ns/iter (+/- 8,306,700)
//! ```

#![no_std]
#![doc(html_root_url = "https://docs.rs/out")]
#![deny(missing_docs)]

#[cfg(feature = "alloc")]
extern crate alloc;

/// Functions for use with slices.
///
/// # Examples
/// ```
/// let mut v = [-5, 4, 1, -3, 2];
/// let max = out::slice::max(&mut v, 3);
/// assert_eq!(max, [1, 2, 4]);
/// assert_eq!(v, [-3, 1, 2, 4, -5]);
/// ```
pub mod slice {
    use core::{cmp::Ordering, mem, slice};

    /// Returns the `n` largest items.
    ///
    /// This sort is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5, 4, 1, -3, 2];
    /// let max = out::slice::max(&mut v, 3);
    /// assert_eq!(max, [1, 2, 4]);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn max<T: Ord>(v: &mut [T], n: usize) -> &mut [T] {
        max_by(v, n, T::cmp)
    }

    /// Returns the `n` smallest items.
    ///
    /// This sort is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5, 4, 1, -3, 2];
    /// let min = out::slice::min(&mut v, 3);
    /// assert_eq!(min, [1, -3, -5]);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn min<T: Ord>(v: &mut [T], n: usize) -> &mut [T] {
        min_by(v, n, T::cmp)
    }

    /// Returns the `n` largest items with a comparator function.
    ///
    /// This sort is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5, 4, 1, -3, 2];
    /// let min = out::slice::max_by(&mut v, 3, |a, b| b.cmp(a));
    /// assert_eq!(min, [1, -3, -5]);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn max_by<T>(v: &mut [T], n: usize, mut cmp: impl FnMut(&T, &T) -> Ordering) -> &mut [T] {
        if n == 0 {
            return &mut [];
        }
        let (mut left, mut right) = v.split_at_mut(n);
        left.sort_by(&mut cmp);
        let mut i = 0;
        while i < right.len() {
            if cmp(&right[i], &left[0]) == Ordering::Less {
                i += 1;
            } else if cmp(&right[i], &left[n / 2]) == Ordering::Greater {
                right.swap(i, 0);
                let mut j = n - 1;
                if cmp(&left[j], &right[0]) == Ordering::Greater {
                    mem::swap(&mut left[j], &mut right[0]);
                    while cmp(&left[j], &left[j - 1]) == Ordering::Less {
                        left.swap(j, j - 1);
                        j -= 1;
                    }
                }
                unsafe {
                    shift_slice_right(&mut left, &mut right);
                }
            } else {
                mem::swap(&mut left[0], &mut right[i]);
                let mut j = 0;
                while j < n - 1 && cmp(&left[j], &left[j + 1]) != Ordering::Less {
                    left.swap(j, j + 1);
                    j += 1;
                }
                i += 1;
            }
        }
        left
    }

    /// Returns the `n` smallest items with a comparator function.
    ///
    /// This sort is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5, 4, 1, -3, 2];
    /// let max = out::slice::min_by(&mut v, 3, |a, b| b.cmp(a));
    /// assert_eq!(max, [1, 2, 4]);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn min_by<T>(v: &mut [T], n: usize, mut cmp: impl FnMut(&T, &T) -> Ordering) -> &mut [T] {
        max_by(v, n, move |a, b| cmp(b, a))
    }

    /// Returns the `n` largest items with a key extraction function.
    ///
    /// This sort is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5_i32, 4, 1, -3, 2];
    /// let max = out::slice::max_by_key(&mut v, 3, |a| a.abs());
    /// assert_eq!(max, [-3, 4, -5]);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn max_by_key<T, K: Ord>(v: &mut [T], n: usize, mut f: impl FnMut(&T) -> K) -> &mut [T] {
        max_by(v, n, |a, b| f(a).cmp(&f(b)))
    }

    /// Returns the `n` smallest items with a key extraction function.
    ///
    /// This sort is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5_i32, 4, 1, -3, 2];
    /// let min = out::slice::min_by_key(&mut v, 3, |a| a.abs());
    /// assert_eq!(min, [-3, 2, 1]);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn min_by_key<T, K: Ord>(v: &mut [T], n: usize, mut f: impl FnMut(&T) -> K) -> &mut [T] {
        min_by(v, n, |a, b| f(a).cmp(&f(b)))
    }

    /// Returns the `n` largest items with a key extraction function.
    ///
    /// The key function is called only once per element, but for simple key functions `sort_by_key`
    /// is likely to be faster.
    ///
    /// This sort is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5_i32, 4, 1, -3, 2];
    /// let max = out::slice::max_by_cached_key(&mut v, 3, |a| a.abs());
    /// assert_eq!(max, [-3, 4, -5]);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn max_by_cached_key<T, K: Ord>(v: &mut [T], n: usize, f: impl FnMut(&T) -> K) -> &mut [T] {
        // Implementation based on https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by_cached_key.
        macro_rules! max_by_cached_key {
            ($t:ty) => {{
                // All elements are unique since they contain the index, so we can use the unstable version.
                let iter = v.iter().map(f).enumerate().map(|(i, k)| (k, i as $t));
                let mut sorted = crate::iter::max_unstable(iter, n);
                for i in 0..n {
                    let mut idx = sorted[i].1;
                    while (idx as usize) < i {
                        idx = sorted[idx as usize].1;
                    }
                    sorted[i].1 = idx;
                    v.swap(i, idx as usize);
                }
                &mut v[..n]
            }};
        }
        // Find the smallest type possible for the index, to reduce the amount of allocation needed.
        let sz_u8 = mem::size_of::<(K, u8)>();
        let sz_u16 = mem::size_of::<(K, u16)>();
        let sz_u32 = mem::size_of::<(K, u32)>();
        let sz_usize = mem::size_of::<(K, usize)>();
        if sz_u8 < sz_u16 && v.len() <= u8::max_value() as usize {
            max_by_cached_key!(u8)
        } else if sz_u16 < sz_u32 && v.len() <= u16::max_value() as usize {
            max_by_cached_key!(u16)
        } else if sz_u32 < sz_usize && v.len() <= u32::max_value() as usize {
            max_by_cached_key!(u32)
        } else {
            max_by_cached_key!(usize)
        }
    }

    /// Returns the `n` smallest items with a key extraction function.
    ///
    /// The key function is called only once per element, but for simple key functions `sort_by_key`
    /// is likely to be faster.
    ///
    /// This sort is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5_i32, 4, 1, -3, 2];
    /// let min = out::slice::min_by_cached_key(&mut v, 3, |a| a.abs());
    /// assert_eq!(min, [-3, 2, 1]);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn min_by_cached_key<T, K: Ord>(v: &mut [T], n: usize, f: impl FnMut(&T) -> K) -> &mut [T] {
        // Implementation based on https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by_cached_key.
        macro_rules! min_by_cached_key {
            ($t:ty) => {{
                // All elements are unique since they contain the index, so we can use the unstable version.
                let iter = v.iter().map(f).enumerate().map(|(i, k)| (k, i as $t));
                let mut sorted = crate::iter::min_unstable(iter, n);
                for i in 0..n {
                    let mut idx = sorted[i].1;
                    while (idx as usize) < i {
                        idx = sorted[idx as usize].1;
                    }
                    sorted[i].1 = idx;
                    v.swap(i, idx as usize);
                }
                &mut v[..n]
            }};
        }
        // Find the smallest type possible for the index, to reduce the amount of allocation needed.
        let sz_u8 = mem::size_of::<(K, u8)>();
        let sz_u16 = mem::size_of::<(K, u16)>();
        let sz_u32 = mem::size_of::<(K, u32)>();
        let sz_usize = mem::size_of::<(K, usize)>();
        if sz_u8 < sz_u16 && v.len() <= u8::max_value() as usize {
            min_by_cached_key!(u8)
        } else if sz_u16 < sz_u32 && v.len() <= u16::max_value() as usize {
            min_by_cached_key!(u16)
        } else if sz_u32 < sz_usize && v.len() <= u32::max_value() as usize {
            min_by_cached_key!(u32)
        } else {
            min_by_cached_key!(usize)
        }
    }

    /// Returns the `n` largest items.
    ///
    /// This sort is unstable (i.e. may reorder equal elements), in-place
    /// (i.e. does not allocate), and typically faster than [`max`](fn.max.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5, 4, 1, -3, 2];
    /// let max = out::slice::max_unstable(&mut v, 3);
    /// assert_eq!(max, [1, 2, 4]);
    /// ```
    pub fn max_unstable<T: Ord>(v: &mut [T], n: usize) -> &mut [T] {
        max_unstable_by(v, n, T::cmp)
    }

    /// Returns the `n` smallest items.
    ///
    /// This sort is unstable (i.e. may reorder equal elements), in-place
    /// (i.e. does not allocate), and typically faster than [`min`](fn.min.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5, 4, 1, -3, 2];
    /// let min = out::slice::min_unstable(&mut v, 3);
    /// assert_eq!(min, [1, -3, -5]);
    /// ```
    pub fn min_unstable<T: Ord>(v: &mut [T], n: usize) -> &mut [T] {
        min_unstable_by(v, n, T::cmp)
    }

    /// Returns the `n` largest items with a comparator function.
    ///
    /// This sort is unstable (i.e. may reorder equal elements), in-place
    /// (i.e. does not allocate), and typically faster than [`max_by`](fn.max_by.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5, 4, 1, -3, 2];
    /// let min = out::slice::max_unstable_by(&mut v, 3, |a, b| b.cmp(a));
    /// assert_eq!(min, [1, -3, -5]);
    /// ```
    pub fn max_unstable_by<T>(
        v: &mut [T],
        n: usize,
        mut cmp: impl FnMut(&T, &T) -> Ordering,
    ) -> &mut [T] {
        if n == 0 {
            return &mut [];
        }
        let (mut left, mut right) = v.split_at_mut(n);
        left.sort_unstable_by(&mut cmp);
        let mut i = 0;
        while i < right.len() {
            if cmp(&left[0], &right[i]) == Ordering::Greater {
                i += 1;
            } else if cmp(&right[i], &left[n / 2]) == Ordering::Greater {
                right.swap(i, 0);
                let mut j = n - 1;
                if cmp(&left[j], &right[0]) == Ordering::Greater {
                    mem::swap(&mut left[j], &mut right[0]);
                    while cmp(&left[j], &left[j - 1]) == Ordering::Less {
                        left.swap(j, j - 1);
                        j -= 1;
                    }
                }
                unsafe {
                    shift_slice_right(&mut left, &mut right);
                }
            } else {
                mem::swap(&mut left[0], &mut right[i]);
                let mut j = 0;
                while j < n - 1 && cmp(&left[j], &left[j + 1]) == Ordering::Greater {
                    left.swap(j, j + 1);
                    j += 1;
                }
                i += 1;
            }
        }
        left
    }

    /// Returns the `n` smallest items with a comparator function.
    ///
    /// This sort is unstable (i.e. may reorder equal elements), in-place
    /// (i.e. does not allocate), and typically faster than [`min_by`](fn.min_by.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5, 4, 1, -3, 2];
    /// let max = out::slice::min_unstable_by(&mut v, 3, |a, b| b.cmp(a));
    /// assert_eq!(max, [1, 2, 4]);
    /// ```
    pub fn min_unstable_by<T>(
        v: &mut [T],
        n: usize,
        mut cmp: impl FnMut(&T, &T) -> Ordering,
    ) -> &mut [T] {
        max_unstable_by(v, n, move |a, b| cmp(b, a))
    }

    /// Returns the `n` largest items with a key extraction function.
    ///
    /// This sort is unstable (i.e. may reorder equal elements), in-place
    /// (i.e. does not allocate), and typically faster than [`max_by_key`](fn.max_by_key.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5_i32, 4, 1, -3, 2];
    /// let max = out::slice::max_unstable_by_key(&mut v, 3, |a| a.abs());
    /// assert_eq!(max, [-3, 4, -5]);
    /// ```
    pub fn max_unstable_by_key<T, K: Ord>(
        v: &mut [T],
        n: usize,
        mut f: impl FnMut(&T) -> K,
    ) -> &mut [T] {
        max_unstable_by(v, n, |a, b| f(a).cmp(&f(b)))
    }

    /// Returns the `n` smallest items with a key extraction function.
    ///
    /// This sort is unstable (i.e. may reorder equal elements), in-place
    /// (i.e. does not allocate), and typically faster than [`min_by_key`](fn.min_by_key.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let mut v = [-5_i32, 4, 1, -3, 2];
    /// let min = out::slice::min_unstable_by_key(&mut v, 3, |a| a.abs());
    /// assert_eq!(min, [-3, 2, 1]);
    /// ```
    pub fn min_unstable_by_key<T, K: Ord>(
        v: &mut [T],
        n: usize,
        mut f: impl FnMut(&T) -> K,
    ) -> &mut [T] {
        min_unstable_by(v, n, |a, b| f(a).cmp(&f(b)))
    }

    /// Shift the left slice to the right while shrinking the right slice.
    ///
    /// ```text
    /// [a, b][c, d, e] -> a [b, c][d, e]
    /// ```
    ///
    /// # Safety
    /// The two slices must be next to each other and `right` can not be empty.
    unsafe fn shift_slice_right<T>(left: &mut &mut [T], right: &mut &mut [T]) {
        let len = left.len();
        let ptr = left.as_mut_ptr();
        *left = slice::from_raw_parts_mut(ptr.add(1), len);
        let len = right.len();
        let ptr = right.as_mut_ptr();
        *right = slice::from_raw_parts_mut(ptr.add(1), len - 1);
    }
}

/// Functions for use with iterators.
///
/// # Examples
/// ```
/// let max = out::iter::max(-10..10, 3);
/// assert_eq!(max, [7, 8, 9]);
/// ```
#[cfg(feature = "alloc")]
pub mod iter {
    use alloc::vec::Vec;
    use core::cmp::Ordering;

    /// Returns the `n` largest items from an iterator.
    ///
    /// This function is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let max = out::iter::max(-10..10, 3);
    /// assert_eq!(max, [7, 8, 9]);
    /// ```
    pub fn max<T: Ord>(iter: impl IntoIterator<Item = T>, n: usize) -> Vec<T> {
        max_by(iter, n, T::cmp)
    }

    /// Returns the `n` smallest items from an iterator.
    ///
    /// This function is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let min = out::iter::min(-10..10, 3);
    /// assert_eq!(min, [-8, -9, -10]);
    /// ```
    pub fn min<T: Ord>(iter: impl IntoIterator<Item = T>, n: usize) -> Vec<T> {
        min_by(iter, n, T::cmp)
    }

    /// Returns the `n` largest items from an iterator with a comparator function.
    ///
    /// This function is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let min = out::iter::max_by(-10_i32..10, 3, |a, b| b.cmp(a));
    /// assert_eq!(min, [-8, -9, -10]);
    /// ```
    pub fn max_by<T>(
        iter: impl IntoIterator<Item = T>,
        n: usize,
        mut cmp: impl FnMut(&T, &T) -> Ordering,
    ) -> Vec<T> {
        let mut v = Vec::with_capacity(n);
        if n == 0 {
            return v;
        }
        let mut iter = iter.into_iter();
        while v.len() < n {
            let item = iter
                .next()
                .expect("`n` can not be larger than the iterator");
            v.push(item);
        }
        v.sort_by(&mut cmp);
        for item in iter {
            if cmp(&item, &v[0]) != Ordering::Less {
                v[0] = item;
                let mut i = 0;
                while i < n - 1 && cmp(&v[i], &v[i + 1]) != Ordering::Less {
                    v.swap(i, i + 1);
                    i += 1;
                }
            }
        }
        v
    }

    /// Returns the `n` smallest items from an iterator with a comparator function.
    ///
    /// This function is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let max = out::iter::min_by(-10_i32..10, 3, |a, b| b.cmp(a));
    /// assert_eq!(max, [7, 8, 9]);
    /// ```
    pub fn min_by<T>(
        iter: impl IntoIterator<Item = T>,
        n: usize,
        mut cmp: impl FnMut(&T, &T) -> Ordering,
    ) -> Vec<T> {
        max_by(iter, n, move |a, b| cmp(b, a))
    }

    /// Returns the `n` largest items from an iterator with a key extraction function.
    ///
    /// This function is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let max = out::iter::max_by_key(-10_i32..10, 3, |a| a.abs());
    /// assert_eq!(max, [-9, 9, -10]);
    /// ```
    pub fn max_by_key<T, K: Ord>(
        iter: impl IntoIterator<Item = T>,
        n: usize,
        mut f: impl FnMut(&T) -> K,
    ) -> Vec<T> {
        max_by(iter, n, |a, b| f(a).cmp(&f(b)))
    }

    /// Returns the `n` smallest items from an iterator with a key extraction function.
    ///
    /// This function is stable, i.e. it preserves the order of equal elements.
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let max = out::iter::min_by_key(-10_i32..10, 3, |a| a.abs());
    /// assert_eq!(max, [-1, 1, 0]);
    /// ```
    pub fn min_by_key<T, K: Ord>(
        iter: impl IntoIterator<Item = T>,
        n: usize,
        mut f: impl FnMut(&T) -> K,
    ) -> Vec<T> {
        min_by(iter, n, |a, b| f(a).cmp(&f(b)))
    }

    /// Returns the `n` largest items from an iterator.
    ///
    /// This sort is unstable (i.e. may reorder equal elements)
    /// and typically faster than [`max`](fn.max.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let max = out::iter::max_unstable(-10..10, 3);
    /// assert_eq!(max, [7, 8, 9]);
    /// ```
    pub fn max_unstable<T: Ord>(iter: impl IntoIterator<Item = T>, n: usize) -> Vec<T> {
        max_unstable_by(iter, n, T::cmp)
    }

    /// Returns the `n` smallest items from an iterator.
    ///
    /// This sort is unstable (i.e. may reorder equal elements)
    /// and typically faster than [`min`](fn.min.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let min = out::iter::min_unstable(-10..10, 3);
    /// assert_eq!(min, [-8, -9, -10]);
    /// ```
    pub fn min_unstable<T: Ord>(iter: impl IntoIterator<Item = T>, n: usize) -> Vec<T> {
        min_unstable_by(iter, n, T::cmp)
    }

    /// Returns the `n` largest items from an iterator with a comparator function.
    ///
    /// This sort is unstable (i.e. may reorder equal elements)
    /// and typically faster than [`max_by`](fn.max_by.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let min = out::iter::max_unstable_by(-10..10, 3, |a, b| b.cmp(a));
    /// assert_eq!(min, [-8, -9, -10]);
    /// ```
    pub fn max_unstable_by<T>(
        iter: impl IntoIterator<Item = T>,
        n: usize,
        mut cmp: impl FnMut(&T, &T) -> Ordering,
    ) -> Vec<T> {
        let mut v = Vec::with_capacity(n);
        if n == 0 {
            return v;
        }
        let mut iter = iter.into_iter();
        while v.len() < n {
            let item = iter
                .next()
                .expect("`n` can not be larger than the iterator");
            v.push(item);
        }
        v.sort_unstable_by(&mut cmp);
        for item in iter {
            if cmp(&item, &v[0]) == Ordering::Greater {
                v[0] = item;
                let mut i = 0;
                while i < n - 1 && cmp(&v[i], &v[i + 1]) == Ordering::Greater {
                    v.swap(i, i + 1);
                    i += 1;
                }
            }
        }
        v
    }

    /// Returns the `n` smallest items from an iterator with a comparator function.
    ///
    /// This sort is unstable (i.e. may reorder equal elements)
    /// and typically faster than [`min_by`](fn.min_by.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let max = out::iter::min_unstable_by(-10..10, 3, |a, b| b.cmp(a));
    /// assert_eq!(max, [7, 8, 9]);
    /// ```
    pub fn min_unstable_by<T>(
        iter: impl IntoIterator<Item = T>,
        n: usize,
        mut cmp: impl FnMut(&T, &T) -> Ordering,
    ) -> Vec<T> {
        max_unstable_by(iter, n, move |a, b| cmp(b, a))
    }

    /// Returns the `n` largest items from an iterator with a key extraction function.
    ///
    /// This sort is unstable (i.e. may reorder equal elements)
    /// and typically faster than [`max_by_key`](fn.max_by_key.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let max = out::iter::max_unstable_by_key(-10_i32..10, 3, |a| a.abs());
    /// assert_eq!(max, [9, -9, -10]);
    /// ```
    pub fn max_unstable_by_key<T, K: Ord>(
        iter: impl IntoIterator<Item = T>,
        n: usize,
        mut f: impl FnMut(&T) -> K,
    ) -> Vec<T> {
        max_unstable_by(iter, n, |a, b| f(a).cmp(&f(b)))
    }

    /// Returns the `n` smallest items from an iterator with a key extraction function.
    ///
    /// This sort is unstable (i.e. may reorder equal elements)
    /// and typically faster than [`min_by_key`](fn.min_by_key.html).
    ///
    /// # Panics
    /// Panics if `n > len`.
    ///
    /// # Examples
    /// ```
    /// let min = out::iter::min_unstable_by_key(-10_i32..10, 3, |a| a.abs());
    /// assert_eq!(min, [1, -1, 0]);
    /// ```
    pub fn min_unstable_by_key<T, K: Ord>(
        iter: impl IntoIterator<Item = T>,
        n: usize,
        mut f: impl FnMut(&T) -> K,
    ) -> Vec<T> {
        min_unstable_by(iter, n, |a, b| f(a).cmp(&f(b)))
    }
}