Suppose you insert (15) if I run this program, the output will be (14 16 17 18 19) How can I make the program to insert the number 15 in the correct position (pos = 1) or any number (n) in it's correct position (pos).
(define list1 '(14 16 17 18 19))
(define lst (list))
(define (insert lst n)
(if (empty? lst)
'()
(foldr cons (list n) lst))) ;The value gets inserted at the end of the list
We have many sorting algorithm like Quicksort, histogram sort, bubble sort.
You can see this Sorting Algorithms or wikipedia.
If n
is bigger than every data inside list which is lst
become '()
we just return (list n)
e.g. (f '() 1) -> '(1)
When n
less or equal to first element we insert in first position.
e.g. (f '(2) 1) -> (cons 1 '(2))
If not we want data like this:
(f '(1 2 4) 3) -> (cons 1 (f '(2 4) 3)) -> (cons 1 (cons 2 (f '(4) 3))) -> (cons 1 (cons 2 (cons 3 '(4)))) -> (list 1 2 3 4)
(define (insert-with-<-order lst n)
(cond
[(empty? lst)
(list n)]
[(<= n (first lst))
(cons n lst)]
[else
(cons (first lst)
(insert-with-<-order (rest lst) n))]))
(insert-with-<-order '(1 1 2 3) 1.5)
(insert-with-<-order '(-2 0.5 1 2 5) 0.1)
(insert-with-<-order '(1 2 3) 4)
Use sort
(define (insert-with-order lst n)
(sort (cons n lst) <))
(insert-with-order '(14 16 17 18 19) 15)