在 Prolog 中对列表进行排序 [英] Sorting a list in Prolog

查看:24
本文介绍了在 Prolog 中对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Prolog 有一种独特的处理方式,尤其是因为实际上每个操作都涉及一种或另一种递归.

Prolog has a unique way of handling things, especially since practically every operation involves recursion of one sort or another.

每种语言都有的一个经典示例是将整数列表按升序排序.

One of the classic examples every language has is sorting a list of integers into ascending order.

对随机整数列表进行排序的最佳方式是什么(不使用太多内置谓词,当然这会排除 sort/2 谓词)?

What is an optimal way (without using too many built-in predicates, which precludes a sort/2 predicate, of course) to sort a random list of integers?

推荐答案

Roman Barták 的 Prolog Programming 网站提供 不同排序算法的示例,以优化的快速排序结束.

Roman Barták's Prolog Programming site gives examples of different sort algorithms, ending with an optimized quicksort.

quick_sort2(List,Sorted):-q_sort(List,[],Sorted).
q_sort([],Acc,Acc).
q_sort([H|T],Acc,Sorted):-
    pivoting(H,T,L1,L2),
    q_sort(L1,Acc,Sorted1),q_sort(L2,[H|Sorted1],Sorted)

这篇关于在 Prolog 中对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆