# Sorting Vector

and a part of it in Rust

## Introduction

Sorting is defined as putting the sequence of elements into an order. The order can be ascending or descending or can be decided using a comparison function.

Sorting is very useful in many applications because it can help in

1. Searching for a given value efficient.
2. Finding the median of the sequence.
3. Merging the sequences.
4. Determining kth largest and smallest elements etc.

Hence, sorting is one of the most important algorithms.

But here, in this article, we will not discuss the algorithm itself. We will learn how to use functions provided in Rust's standard crate to sort the vector.

## sort() method

The `sort()` method is used to sort the whole array. It is stable sorting algorithm, inspired by Timsort

For Example

`fn main() {    let mut vecky = vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1];    vecky.sort();    println!("{:?}", vecky);}`

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Time Complexity (Average case) : O(n log(n) )
Space Complexity : O (n)

## sort_unstable() method

The `sort_unstable()` method, as suggested by name, is unstable sorting method, and can provide better performance than stable sort in some cases. It uses pattern defeating quick sort algorithm to sort the elements.

For Example

`fn main() {    let mut vecky = vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1];    vecky.sort_unstable();    println!("{:?}", vecky);}`

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Time Complexity (Average case) : O(n log(n) )
Space Complexity : O ( log (n) )

Note : Although the time complexity is similar, `sort_unstable()` can be faster than stable sort.

## Sort a slice of a Vector

We can use both `sort()` and `sort_unstable()` to sort a slice of a vector. We simply have to use slice of the vector instead of vector itself. For example

`vecky[0..5].sort();`

or

`vecky[0..5].sort_unstable();`

Output

[6, 7, 8, 9, 10, 5, 4, 3, 2, 1]

## sort_by() custom key

To sort a vector using our custom function, we have to use `sort_by()` method. We can simply provide a method to use as function in this.

For example, to sort a vector in descending order, we can define a compare function

`fn compare(a: &i32, b: &i32) ->std::cmp::Ordering{    if a<b {        return std::cmp::Ordering::Greater;    }    if a==b{        return  std::cmp::Ordering::Equal;    }    return std::cmp::Ordering::Less;}`

and use it

`fn main() {    let mut vecky = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];    vecky[0..5].sort_by(compare);    println!("{:?}", vecky);}`

Output

[5, 4, 3, 2, 1, 6, 7, 8, 9, 10]

Note : 1. The compare function must return value of `std::cmp::Ordering` type. 2. We can alternatively use `sort_by(|a, b| compare(a, b))` in case you need it.

## sort_unstable_by()

We can use `sort_unstable_by()` in similar manner. For example

```fn compare(a: &i32, b: &i32) ->std::cmp::Ordering{    if a<b {        return std::cmp::Ordering::Greater;    }    if a==b{        return  std::cmp::Ordering::Equal;    }    return std::cmp::Ordering::Less;}
fn main() {    let mut vecky = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];    vecky[0..5].sort_unstable_by(compare);    println!("{:?}", vecky);}```

Output

[5, 4, 3, 2, 1, 6, 7, 8, 9, 10]

## Conclusion

Sorting is putting the sequence of elements into an order, and is a very commonly used function. In this article, we saw how to sort a vector using both stable sort and unstable sort and also, how to sort using a compare function in Rust Language.

Thank You
{"ft_lang_label":"__label__en","ft_lang_prob":0.66523814,"math_prob":0.95662147,"size":3250,"snap":"2023-40-2023-50","text_gpt3_token_len":1044,"char_repetition_ratio":0.1241528,"word_repetition_ratio":0.23339659,"special_character_ratio":0.32646152,"punctuation_ratio":0.2862363,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99250954,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-12-06T18:27:12Z\",\"WARC-Record-ID\":\"<urn:uuid:3310dcea-c3e9-4e75-be52-39d2f85b5c64>\",\"Content-Length\":\"95574\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:2c9abd59-ec36-4792-a8c9-45b7d87e9768>\",\"WARC-Concurrent-To\":\"<urn:uuid:034abd1a-d5c6-4cc2-be78-33018ef614f2>\",\"WARC-IP-Address\":\"104.21.49.203\",\"WARC-Target-URI\":\"https://rustp.org/data-structures/sorting-vector/\",\"WARC-Payload-Digest\":\"sha1:72MSWLFW7NT4JY2E7MJVGBB2OG7PTRY4\",\"WARC-Block-Digest\":\"sha1:UOZU7M3KBQI6NNBW3ESXDOZV7Z3ZKDCZ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-50/CC-MAIN-2023-50_segments_1700679100602.36_warc_CC-MAIN-20231206162528-20231206192528-00110.warc.gz\"}"}