我如何快速排序这个类型马,它是一个2元组,由一个字符串(马的名字)和一个Int(马的身高厘米)组成



我正试图按每匹马的高度按升序快速排序。例如[("Thunder",125),("Lightning",115),("Bolt",135)]。

我试过以下方法;

type Horse = (String, Int)
sort_horse_list :: [Horse] -> [Horse]
sort_horse_list horses = quick_sort horses
(h1 h2 -> snd h1 <= snd h2)

期望输出为[("Lightning",115),("Thunder",125),("Bolt",135)]。

我不知道你使用的是什么类型的quick_sort函数,因为已经被left - roundabout评论过了。如果不知道你正在使用的快速排序算法的类型,很难给你一个确切的答案。然而,我确实使用sortBycomparing函数创建了一个实现。sortBy函数不使用快速排序(它使用归并排序),所以如果您必须使用快速排序,这不是一个有效的解决方案:

import Data.List
import Data.Ord
type Horse = (String, Int)
sort_horse_list :: [Horse] -> [Horse]
sort_horse_list = sortBy (comparing $ snd)

可以这样使用:

main :: IO ()
main = let xs = [("Thunder",125),("Lightning",115),("Bolt",135)] in do
print (sort_horse_list xs)

最新更新