Prolog 对每个位置有两个元素的列表进行排序
我目前正在研究 Prolog 快速排序。
Prolog 中的快速排序规则是:
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).
pivoting(H, [], [], []).
pivoting(H, [X|T], L, [X|G]) :-X =< H, pivoting(H, T, L, G).
pivoting(H, [X|T], [X|L], G) :-X > H, pivoting(H, T, L, G).
它对如下所示的列表进行排序: [1,2,5,3,4]
但是,我的列表当前采用这种格式,每个位置有 2 个元素:
<代码>[(18427840,wplabuan), (801267209,柔佛), (258368353,吉兰丹), (381775777,吉打), (443783415,沙巴), (188532090,马六甲), (540920146,wpkualalumpur), (380758940,pulaupinang), (285145365,彭亨), (1447204206,雪兰莪), (243650261,negerisembilan), (47633359,perlis), (455013525,perak), (26449297,wpputrajaya), (204709755,terengganu), (498580177,sarawak)]
我可以知道如何对上面的列表进行排序吗使用快速排序?
谢谢。
我希望具有总和和状态(总和,状态)的列表根据总和按升序排序。
I am currently working on Prolog quick sorting.
The quicksort rule in Prolog is:
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).
pivoting(H, [], [], []).
pivoting(H, [X|T], L, [X|G]) :-X =< H, pivoting(H, T, L, G).
pivoting(H, [X|T], [X|L], G) :-X > H, pivoting(H, T, L, G).
It sorts lists that look like this: [1,2,5,3,4]
However, my list currently is in this format with each position having 2 elements:
[(18427840,wplabuan), (801267209,johor), (258368353,kelantan), (381775777,kedah), (443783415,sabah), (188532090,melaka), (540920146,wpkualalumpur), (380758940,pulaupinang), (285145365,pahang), (1447204206,selangor), (243650261,negerisembilan), (47633359,perlis), (455013525,perak), (26449297,wpputrajaya), (204709755,terengganu), (498580177,sarawak)]
May I know how should I sort the list above using quicksort?
Thank you.
I want the list with sum and state (sum, state) to be sorted in ascending order according to the sum.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
目标
E1 =< E2
成功当且仅当算术表达式E1
表示的 number 小于或等于算术表达式E2
。例如:但是请注意,运算符
=<
不能用于比较结构:要比较结构,请使用 术语的标准顺序,您可以使用运算符
@=<
:类似地,比较结构时,还可以使用运算符
@<
、@>
、@>=
。因此,要解决该问题,您可以修改代码如下:
The goal
E1 =< E2
succeeds iff the number denoted by the arithmetic expressionE1
is less than or equal to the number denoted by the arithmetic expressionE2
. For example:Note, however, that the operator
=<
cannot be used to compare structures:To compare structures, w.r.t. the standard order of terms, you can use the operator
@=<
:Analogously, when comparing structures, you can also use operators
@<
,@>
,@>=
.Thus, to solve the problem, you can modify your code as follows: