Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

用rust写一个快速排序算法

  1. User

    用rust写一个快速排序算法

  2. Assistant

    下面是一个用Rust编写的快速排序算法的示例:

    fn quicksort<T: Ord>(arr: &mut [T]) {
        if arr.len() <= 1 {
            return;
        }
        let pivot_index = partition(arr);
        quicksort(&mut arr[0..pivot_index]);
        quicksort(&mut arr[pivot_index + 1..]);
    }
    
    fn partition<T: Ord>(arr: &mut [T]) -> usize {
        let pivot_index = arr.len() - 1;
        let mut i = 0;
        for j in 0..pivot_index {
            if arr[j] <= arr[pivot_index] {
                arr.swap(i, j);
                i += 1;
            }
        }
        arr.swap(i, pivot_index);
        i
    }
    
    fn main() {
        let mut arr = [9, 3, 5, 2, 6, 1, 4, 8, 7];
        quicksort(&mut arr);
        println!("{:?}", arr);
    }
    

    这个示例使用泛型来支持任意类型的排序,只要实现了Ord trait。quicksort函数用于递归地进行排序,partition函数用于将数组分区并返回枢轴(pivot)的索引。main函数示例了如何使用该排序算法。运行该程序会输出[1, 2, 3, 4, 5, 6, 7, 8, 9],表示数组已经按升序排序。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.