序言计数排序



因此,我使用Eclipse 6.1创建了计数排序(https://en.wikipedia.org/wiki/counting_sort)程序。它可以很好地排序,但是只能在控制台中编写排序列表,而不是将其返回为第二个变量。那么如何使其作为变量返回排序列表?
例如:

mysort([1,1,6,7,4,1.5,11,6,7],Z) 

是在控制台中写入([7,7,7,6,6,4,1,1]),这是正确的答案(它分类为0到10)。但变量为z = z,而不是z,=([7,7,7,6,6,4,1,1])

      build(_,0,[]).  %create list with ARG1 value , ARG2 size, and write to ARG3
      build(X,N1,[X|L]) :- N1 > 0, N is N1 - 1, build(X,N,L). 
      build(X,N1,[X]):- N1>0, N1 is N - 1, build(X,N,[]).  
      build_list(X,N):-build(0,N,X).%create list with ARG1 value , ARG2 size, and write to ARG3
      sum_list([], 0).% ARG1 list sum, write to ARG2
      sum_list([H|T], Sum) :-
         sum_list(T, Rest),
         Sum is H + Rest.
      replace([_|T], 0, X, [X|T]).%replace in ARG1 list,  ARG2 index with           ARG3 value,return as ARG4
      replace([H|T], I, X, [H|R]):- I > -1, NI is I-1, replace(T, NI, X, R), !.
      replace(L, _, _, L).
      increment_nth_in_list( [] , [],_ ) .%Increment element in ARG1, return as ARG2, increment element on ARG3 position
      increment_nth_in_list( [X|Xs] , [Y|Ys],N) :-
        (N=0->Y is X+1,N1 is N-1;
        N1 is N-1,Y is X),
        increment_nth_in_list(Xs,Ys,N1).    
      decrement_nth_in_list( [] , [],_ ) .%Decrement element in ARG1, return as ARG2, Decrement element on ARG3 position
      decrement_nth_in_list( [X|Xs] , [Y|Ys],N) :- 
        (N=0->Y is X-1,N1 is N-1;
         N1 is N-1,Y is X),
        decrement_nth_in_list(Xs,Ys,N1).    
      mysort([],[]).
      mysort([_],[]).
      mysort(Sorting,Sorted):-%Starting sort
      build_list(Amounts_of,10),%create list from 0 to 10 (MAX)
      count_numbers(Sorting,Amounts_of).%starting to count numbers
      count_numbers([Sortinghead|Sortingtail],Amount_of):-%counting numbers from ARG1 and writing to ARG2
      increment_nth_in_list(Amount_of,NewAmount,Sortinghead),
      length(Sortingtail,Z),
      (Z>0->count_numbers(Sortingtail,NewAmount);
      sum_list(NewAmount,Sum),build_list(Sorted,Sum),length(Sorted,L),fill_list(NewAmount,Sorted,0,L)
      ).
      fill_list([],A,_,_):-write(A).
      fill_list([Amount_of_Head|[]],[Sorted],N,L).
      fill_list([Amount_of_Head|Amount_of_Tail],Sorted,N,L):-%Filling ARG2           based on values in ARG1,with ARG3 values on ARG4 position.
      Amount_of_Head>0-          >decrement_nth_in_list([Amount_of_Head|Amount_of_Tail],NewAmount,0),L1 is L-          1,replace(Sorted,L1,N,NewSorted),fill_list(NewAmount,NewSorted,N,L1)
      ;N1 is N+1,fill_list(Amount_of_Tail,Sorted,N1,L).

呼叫中的第二个参数 Z对应于 mysort/2的最后一个子句中的变量 Sorted。但是该子句从不使用该变量,因此它永远不可能绑定到解决方案。您将必须在完成write的同一时刻将参数添加到fill_list/4count_numbers/2中,并将其绑定到解决方案。(您可能能够重复使用现有参数;您的代码格式不佳,并且您的变量名称无助于理解。)

最新更新