Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a LinkedList with just the standard library?

Tags:

rust

Vec provides a sort method (through Deref implementation), but LinkedList does not. Is there a generic algorithm somewhere in the Rust standard library that allows sorting of LinkedLists?

like image 328
wspeirs Avatar asked Jun 02 '15 14:06

wspeirs


People also ask

How do you sort a simple linked list?

Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list 2) Traverse the given list, do following for every node. ......a) Insert current node in sorted way in sorted or result list. 3) Change head of given linked list to head of sorted (or result) list.

How can we sort a linked list?

We can sort the LinkedList by many sorting techniques:Bubble sort. Insertion sort. Quick sort. Merge sort.

What is the fastest way to sort a linked list?

Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.

Is linked list sorted by default?

LinkedList. The sort() method is defined in the List interface and it is a default method. Let's take an example of LinkedList and sort the objects of LinkedList. If you are not familiar with the Comparator interface then read the Comparator interface first.


1 Answers

I don't think there is a built-in way to do it. However, you can move the list contents into a Vec, sort it and turn it back into a linked list:

let mut vec: Vec<_> = list.into_iter().collect();
vec.sort();
let list: LinkedList<_> = vec.into_iter().collect();

This idea is not even remotely as bad as it may seem - see here. While relatively fast algorithms for sorting a linked list do exist, they won't give you as much of cache performance as flat array sorting may do.

like image 156
Vladimir Matveev Avatar answered Oct 09 '22 09:10

Vladimir Matveev