Binary Search - LISP

Program:
;;BINARYSEARCH
(defun binsearch(n)
    (format t "~&<<BINARYSEARCH>>~&")
    (bsreadn n)
    (bssortn n)
    (format t "~&Enter the number to be searched:")
    (setf p (read))
    (setf flag 1)
    (setf first 0)
    (setf last (- n 1))
    (dotimes (x n t)
        (setf mid (floor (+ first last) 2))
        (if (= (aref arr mid) p)(setf flag 0))
        (cond
            ( (>(aref arr mid) p) (setf last (- mid 1)))
            ( (<(aref arr mid) p) (setf first (+ mid 1)))
        )
    )
    (if (= flag 1)
        (format t "Number Not found..."))
    (if (= flag 0)
        (format t "Number found..."))
)
(defun bsreadn(n)
    (setf arr (make-array n))
    (format t "Enter the ~d numbers:" n)
    (dotimes (x n t)
        (setf (aref arr x) (read))
    )
)
                        ;;http://www.2k8618.blogspot.com/
(defun bssortn(n)
    (do (( i 1 (+ i 1))) ((= i n))
        (do ((j 0 (+ j 1))) ((= j (- n 1)))
            (if (> (aref arr j) (aref arr (+ j 1)))
                (bswap j (+ j 1))
            )
        )
    )
    (format t "Sorting....")
    (bprintn n)
)
(defun bprintn(n)
    (dotimes(x n t)
        (print (aref arr x))
    )
)
(defun bswap(x y)
    (setf temp (aref arr x))
    (setf (aref arr x) (aref arr y))
    (setf (aref arr y) temp)
)

Output:
Break 2 [3]> (load 'bin.lsp)
;;  Loading file bin.lsp ...
;;  Loaded file bin.lsp
T
Break 2 [3]> (binsearch 5)
<<BINARYSEARCH>>
Enter the 5 numbers:5
4
3
2
1
Sorting....
1
2
3
4
5
Enter the number to be searched:3
Number found...
NIL
Break 2 [3]> (binsearch 5)
<<BINARYSEARCH>>
Enter the 5 numbers:1
4
2
3
5
Sorting....
1
2
3
4
5
Enter the number to be searched:6
Number Not found...
NIL
Break 2 [3]>

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...