How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Prolog programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Prolog programming language

Table of Contents

Problem Statement

An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:

The algorithm is as follows (from wikipedia): Writing the algorithm for integers will suffice.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Prolog programming language

Source code in the prolog programming language

insert_sort(L1,L2) :-
  insert_sort_intern(L1,[],L2).
 
insert_sort_intern([],L,L).
insert_sort_intern([H|T],L1,L) :-
  insert(L1,H,L2),
  insert_sort_intern(T,L2,L).
 
insert([],X,[X]).
insert([H|T],X,[X,H|T]) :-
  X =< H,
  !.
insert([H|T],X,[H|T2]) :-
  insert(T,X,T2).


% insertion sort
isort(L, LS) :-
	foldl(insert, [], L, LS).


% foldl(Pred, Init, List, R).
foldl(_Pred, Val, [], Val).
foldl(Pred, Val, [H | T], Res) :-
	call(Pred, Val, H, Val1),
	foldl(Pred, Val1, T, Res).

% insertion in a sorted list
insert([], N, [N]).

insert([H | T], N, [N, H|T]) :-
	N =< H, !.

insert([H | T], N, [H|L1]) :-
	insert(T, N, L1).


  

You may also check:How to resolve the algorithm Roman numerals/Decode step by step in the Raku programming language
You may also check:How to resolve the algorithm Hofstadter Q sequence step by step in the Tailspin programming language
You may also check:How to resolve the algorithm Infinity step by step in the Wren programming language
You may also check:How to resolve the algorithm Deceptive numbers step by step in the Factor programming language
You may also check:How to resolve the algorithm Machine code step by step in the M2000 Interpreter programming language