is_sorted

Function is_sorted 

Source
pub fn is_sorted<T>(collection: &[T]) -> bool
where T: PartialOrd,
Expand description

Determines if a collection is sorted in ascending order.

This function checks whether the elements in the provided slice are in non-decreasing order. It iterates through the slice and compares each element with its predecessor.

Time Complexity: O(n), where n is the number of elements in the collection.

§Arguments

  • collection - A slice of items to be checked for sorted order.

§Type Parameters

  • T - The type of elements in the collection. Must implement PartialOrd.

§Returns

  • true if the collection is sorted in ascending order.
  • false otherwise.

§Examples

use lowdash::is_sorted;

let numbers = vec![1, 2, 3, 4, 5];
assert_eq!(is_sorted(&numbers), true);
use lowdash::is_sorted;

let numbers = vec![5, 4, 3, 2, 1];
assert_eq!(is_sorted(&numbers), false);
use lowdash::is_sorted;

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
struct Person {
    name: String,
    age: u32,
}

let people = vec![
    Person { name: "Alice".to_string(), age: 25 },
    Person { name: "Bob".to_string(), age: 30 },
    Person { name: "Carol".to_string(), age: 35 },
];
assert_eq!(is_sorted(&people), true);
use lowdash::is_sorted;

let floats = vec![1.1, 2.2, 3.3, 4.4];
assert_eq!(is_sorted(&floats), true);
use lowdash::is_sorted;

let floats = vec![1.1, std::f64::NAN, 3.3];
// Note: Any comparison with NaN returns false, so the slice is not considered sorted.
assert_eq!(is_sorted(&floats), false);