Google News
logo
Prolog - Interview Questions
How can you implement a custom sorting algorithm in Prolog?
How to implement a custom sorting algorithm in Prolog :
sort(List, Sorted) :-
  quicksort(List, [], Sorted).

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

pivoting(H, T, L1, L2) :-
  choose_pivot(H, T, Pivot),
  partition(T, Pivot, L1, L2).

choose_pivot(H, T, Pivot) :-
  length(T, N),
  select(N div 2, T, Pivot).

partition(List, Pivot, Smaller, Larger) :-
  smaller_than(Pivot, List, Smaller),
  append(Smaller, [Pivot], List1),
  not(smaller_than(Pivot, List1)),
  append(List1, Larger, List).

smaller_than(Pivot, [H|T], Smaller) :-
  H < Pivot,
  Smaller = [H|T].

smaller_than(Pivot, [], Smaller).​
This code implements a quicksort algorithm in Prolog. The sort/3 predicate takes a list as input and returns a sorted list as output. The quicksort/3 predicate recursively sorts the list by choosing a pivot element and partitioning the list into two smaller lists, one containing elements smaller than the pivot and the other containing elements larger than the pivot. The pivoting/3 predicate chooses a pivot element by randomly selecting an element from the list. The partition/3 predicate partitions the list into two smaller lists based on the pivot element. The smaller_than/3 predicate checks if an element is smaller than a pivot element.
Advertisement