Showing posts with label String Sort. Show all posts
Showing posts with label String Sort. Show all posts

String Sort - LISP

Program:

Download Runnable Code

;;BUBBLESORT (STRING)

(defun breadn(n)
(setf arr (make-array n))
(format t "Enter the strings:~&")
(dotimes (x n t)
(setf (aref arr x) (read))))


(defun bprintn(n)
(dotimes(x n t)
    (print (aref arr x))))
(defun swap(x y)
    (setf temp (aref arr x))
    (setf (aref arr x) (aref arr y))
    (setf (aref arr y) temp)
)

(defun bsortn ( n )
    (breadn n);;(bprintn n)
    (do (( i 1 (+ i 1)))
    ((= i n))
    (setf k (- n 1))
    (do((j 0 (+ j 1    )))
    ((= j k))
    (setf m (+ j 1))
    (if (string> (aref arr j) (aref arr m))
        (swap j m))
))
    (bprintn n)
)
Output:
Break 2 [4]> (load 'bbs.lsp)
;; Loading file bbs.lsp ...
;; Loaded file bbs.lsp
T
Break 2 [4]> (bsortn 5)
Enter the strings:
orange
guava
apple
banana
mango

APPLE
BANANA
GUAVA
MANGO
ORANGE
T
Break 2 [4]>

Download

Sort String Lexicographically

Program:
#include<stdio.h>
#include<string.h>
main()
{
    char s[20][20],t[20];
    int i,j,n;
    printf("Enter the number of strings:\n");
    scanf("%d",&n);
    printf("Enter the strings:\n");
    for(i=0;i<n;i++)
        scanf("%s",s[i]);
    for(i=0;i<n;i++)
        for(j=i+1;j<n;j++)
        {
            if(strcmp(s[i],s[j])>0)
            {
                strcpy(t,s[i]);
                strcpy(s[i],s[j]);
                strcpy(s[j],t);
            }
        }
    printf("\nAfter sorting:\n");
    for(i=0;i<n;i++)
        printf("%s\n",s[i]);
}

Output:
nn@linuxmint ~ $ gcc c17.c
nn@linuxmint ~ $ ./a.out
Enter the number of strings:
5
Enter the strings:
banana
apple
guava
pineapple
orange

After sorting:
apple
banana
guava
orange
pineapple
nn@linuxmint ~ $
Related Posts Plugin for WordPress, Blogger...