← Back to Rust Course | Chapter 9: Collections | Lesson 6 of 6

Collections को Sort करना

Sorting किसी list में हर चीज़ को एक neat, predictable order में डालता है, किताबों को सबसे छोटी से सबसे लंबी तक arrange करने जैसा।
Syntax
rust
vec.sort();
vec.sort_by(|a, b| a.cmp(b));
vec.sort_by_key(|item| item.field);

Basic Sorting

.sort() एक mutable Vec के elements को जगह पर, ascending order में sort करता है, जब तक element type Ord trait implement करे, जो ज़्यादातर built-in types करते हैं।

उदाहरण: Basic Sorting

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `numbers`, initialized to `vec![5, 1, 4, 2, 3]`
    let mut numbers = vec![5, 1, 4, 2, 3];
    numbers.sort();
    // Print "{:?}" to the console, substituting in `numbers` (with a trailing newline)
    println!("{:?}", numbers);
}

Sorting by a Key

.sort_by_key(|item| key) हर एक से derive की गई एक value के आधार पर elements sort करता है, जो structs को एक particular field से sort करते समय सुविधाजनक है।

उदाहरण: Sorting by a Key

markup
// Define a struct `Person` to group related fields together
struct Person {
    name: String,
    age: u32,
}

// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `people`, initialized to `vec![`
    let mut people = vec![
        Person { name: String::from("Bob"), age: 25 },
        Person { name: String::from("Ann"), age: 30 },
    ];
    people.sort_by_key(|p| p.age);
    // Loop over `&people`, binding each item to `p`
    for p in &people {
        // Print "{}: {}" to the console, substituting in `p.name, p.age` (with a trailing newline)
        println!("{}: {}", p.name, p.age);
    }
}

Custom Comparisons with sort_by

.sort_by(|a, b| ...) आपका अपना comparator function प्रदान करके ordering पर पूरा control देता है, descending order या natural ordering न रखने वाले types के लिए उपयोगी।

उदाहरण: Custom Comparisons with sort_by

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `numbers`, initialized to `vec![3, 1, 4, 1, 5]`
    let mut numbers = vec![3, 1, 4, 1, 5];
    numbers.sort_by(|a, b| b.cmp(a));
    // Print "{:?}" to the console, substituting in `numbers` (with a trailing newline)
    println!("{:?}", numbers);
}

Sorting Floating-Point Numbers

Floating-point numbers Ord implement नहीं करते क्योंकि NaN को meaningfully compare नहीं किया जा सकता, इसलिए इन्हें sort करना plain .sort() के बजाय .sort_by() के अंदर partial_cmp उपयोग करता है।

उदाहरण: Sorting Floating-Point Numbers

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `prices`, initialized to `vec![9.99, 1.50, 5.25]`
    let mut prices = vec![9.99, 1.50, 5.25];
    prices.sort_by(|a, b| a.partial_cmp(b).unwrap());
    // Print "{:?}" to the console, substituting in `prices` (with a trailing newline)
    println!("{:?}", prices);
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. floats के एक Vec पर .sort() call करना, जो compile होने में fail होता है क्योंकि floats Ord implement नहीं करते -- इसके बजाय partial_cmp के साथ .sort_by() चाहिए।
  2. यह भूल जाना कि .sort() को Vec binding को mutable होना चाहिए, क्योंकि यह elements को जगह पर sort करता है।
  3. .sort() उपयोग करना जब एक stable custom order चाहिए, ज़्यादा control के लिए .sort_by_key() या .sort_by() के बजाय।
चैप्टर सारांश
  • .sort() एक Vec को जगह पर ascending order में sort करता है, elements को Ord implement करना चाहिए।
  • .sort_by_key(|x| ...) elements के natural order के बजाय एक derived key के आधार पर sort करता है।
  • .sort_by(|a, b| ...) comparison पर पूरा custom control देता है, descending order या floats के लिए उपयोगी।
  • Rust का sort stable है, मतलब बराबर elements अपना original relative order बनाए रखते हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.