Write A Java Program For Sorting A Given List of Names in Ascending Order Using Bubble Sort Algorithm

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 26

1.

Write a Java program for sorting a given list of names in ascending order using bubble sort
algorithm.
class SortNames
{
public void sort(String[] a)
{
int i, pass, n = a.length;
String tmp;
for( pass = 0; pass n; pass!! )
{
for( i = 0; i n"pass"#; i!! )
if( (($omparable)a[i]).compare%o(a[i!#]) & 0)
{
tmp = a[i]; '' S(ap a[i], a[i!#]
a[i] = a[i!#];
a[i!#] = tmp;
)
)
)
)
'''''''''''''''''''''''''' SortNamesDemo.java ''''''''''''''''''''
class Sort*ames+emo
{
public static void main(String[] args)
{
Sort*ames sn = ne( Sort*ames();
String[] names =
{,-amu,, ,.ohn,, ,/nu,, ,0ri1a,, ,2asha,, ,0rem,);
int i;
System.out.println("Unsorted names:")
for(i=0; i names.length; i!!)
S1stem.out.println(names[i]);
sn.sort(names);
S1stem.out.println(,Sorted names3,);
for(i=0; i names.length; i!!)
S1stem.out.println(names[i]);
}
}
Output of this program is:
4nsorted names3
-amu
.ohn
/nu
0ri1a
2asha
0rem
Sorted names3
/nu
2asha
.ohn
0rem
0ri1a
-amu
2. Write Java programs that use both recursive and non!recursive functions for implementing the follo"ing
searching methods:
(a) #inear search
(b) $inary search
Linear search
(a) The simplest form of a search is the linear search. This technique is meant for searching a particular item in an
unsorted data set in a sequential manner until the desired data item is found. Linear search is easy to write and
efficient for short lists, but inefficient for long ones. To find any element in a long array (list), there are far more
efficient methods, proided that the array is sorted. ! program for linear search is as follows.
Program 2(a): Iterative Linear search
class 5inearSearch+emo
{
static 6b7ect[] a = { 89, :;, #<;, <, ;0, :=, #>?, 90 );
static 6b7ect @e1 = #>?;
public static void main(String args[])
{
if( linearSearch() )
S1stem.out.println(@e1 ! , found in the list,);
else
S1stem.out.println(@e1 ! , not found in the list,);
)
static boolean linearSearch()
{
for( int i=0; ia.length; i!!)
if(@e1 == a[i]) return true;
return false;
)
}
Program 2(a): Recursive Linear search
class -ecursive5inearSearch+emo
{
static 6b7ect[] a = { 89, :;, #<;, <, ;0, :=, #>?, 90 );
static 6b7ect @e1 = :=;
public static void main(String args[])
{
if( linearSearch(a.length"#) )
S1stem.out.println(@e1 ! , found in the list,);
else
S1stem.out.println(@e1 ! , not found in the list,);
)
static boolean linearSearch(int n)
{
if( n " # ) return false$
if(%ey && a'n()
return true;
else
return linearSearch(n"#);
)
}
Binary search
(b) Binary search is a simple method of accessing a particular item in a sorted (ordered) data set. ! search for a
particular item with a certain %ey alue resembles the search for a name in telephone directory or a word in a
dictionary. The appro)imate middle item of the data set is located, and its %ey alue is e)amined. *f its alue is too
high, then the %ey of the middle element of the first half of the set is e)amined and procedure is repeated on the first
half until the required item is found. *f the alue is too low, then the %ey of the middle entry of the second half of the
data set is tried and the procedure is repeated on the second half. This process continues until the desired %ey is found
or search interal becomes empty. The binary search algorithm is based on binary search tree.
Program 2(b): Iterative Binary search
class 2inar1Search+emo
{
static 6b7ect[] a = { ,/0,, ,A/,, ,BC,, ,B0,, ,6-,, ,%*,, ,40,, ,D2,);
static 6b7ect @e1 = ,40,;
public static void main(String args[])
{
if( binar1Search() )
S1stem.out.println(@e1 ! , found in the list,);
else
S1stem.out.println(@e1 ! , not found in the list,);
)
static boolean binar1Search()
{
int c, mid, lo( = 0, high = a.length"#;
(hile( lo( = high)
{
mid = (lo( ! high)'>;
c = (($omparable)@e1).compare%o(a[mid]);
if( c 0) high = mid"#;
else if( c & 0) lo( = mid!#;
else return true;
)
return false;
)
)
Program2(b): Recursive Binary search
class -ecursive2inar1Search+emo
{
static 6b7ect[] a = { ,/0,, ,A/,, ,BC,, ,B0,, ,6-,, ,%*,, ,40,, ,D2,);
static 6b7ect @e1 = ,E0,;
public static void main(String args[])
{
if( binar1Search(0, a.length"#) )
S1stem.out.println(@e1 ! , found in the list,);
else
S1stem.out.println(@e1 ! , not found in the list,);
)
static boolean binar1Search(int lo(, int high)
{
if( lo( & high ) return false;
int mid = (lo( ! high)'>;
int c = (($omparable)@e1).compare%o(a[mid]);
if( c 0) return binar1Search(lo(, mid"#);
else if( c & 0) return binar1Search(mid!#, high);
else return true;
)
)
=. +rite ,aa programs to implement the List !-T using arrays and lin%ed lists.
List ADT
The elements in a list are of generic type 6b7ect. The elements form a linear structure in which list elements follow
one after the other, from the beginning of the list to its end. The list !-T supports the following operations:
createList(int n): .reates (initially) a list with n nodes.
Input: integer$ Output: /one
insertFirst(obj): *nserts ob0ect obj at the beginning of a list.
Input: Ob0ect$ Output: /one
insertAfter(obj, obj p): *nserts ob0ect obj after the obj p in a list.
Input: Ob0ect and position$ Output: /one
obj deleteFirst(): -eletes the ob0ect at the beginning of a list.
Input: /one$ Output: -eleted ob0ect obj.
obj deleteAfter(obj p): -eletes the ob0ect after the obj p in a list.
Input: 1osition$ Output: -eleted ob0ect obj.
boolean isEmpty(): 2eturns a boolean indicating if the list is empty.
Input: /one$ Output: boolean (true or false).
int size(): 2eturns the number of items in the list.
Input: /one$ Output: integer.
Type Ob0ect may be any type that can be stored in the list. The actual type of the ob0ect will be proided by the user.
The !-T is translated into a ,aa interface in the following program.
public interface List
{
public void createList(int n);
public void insertFirst(6b7ect ob);
public void insertAfterb7ect ob, 6b7ect pos);
public 6b7ect deleteFirst();
public 6b7ect deleteAfter(6b7ect pos);
public boolean isEmpty();
public int size();
)
class ArrayList implements List
{
class Node
{ 6b7ect data;
int neFt;
*ode(6b7ect ob, int i) 33 constructor
{ data = ob;
neFt = i;
)
)
int B/ESGHI; 33 ma) number of nodes in the list
*ode list[]; 33 create list array
int head, count; 33 count: current number of nodes in the list
/rra15ist( int s) 33 constructor
{ B/ESGHI = s;
list = ne( *ode[B/ESGHI];
)
public void initializeList()
{ for( int p = 0; p B/ESGHI"#; p!! )
list[p] = ne( *ode(null, p!#);
list[B/ESGHI"#] = ne( *ode(null, "#);
)
public void createList(int n) 33 create 4n5 nodes
{ int p;
for( p = 0; p n; p!! )
{
list[p] = ne( *ode(##!##Jp, p!#);
count!!;
)
list[p"#].neFt = "#; 33 end of the list
)
public void insertFirst(6b7ect item)
{
if( count == B/ESGHI )
{ S1stem.out.println(,JJJ5ist is K455,);
return;
)
int p = get*ode();
if( p L= "# )
{
list[p].data = item;
if( isImpt1() ) list[p].neFt = "#;
else list[p].neFt = head;
head = p;
count!!;
)
)
public void insertAfter(6b7ect item, 6b7ect F)
{
if( count == B/ESGHI )
{ S1stem.out.println(,JJJ5ist is K455,);
return;
)
int M = get*ode(); 33 get the aailable position to insert new node
int p = find(F); 33 get the inde) (position) of the Ob0ect F
if( M L= "# )
{ list[M].data = item;
list[M].neFt = list[p].neFt;
list[p].neFt = M;
count!!;
)
)
public int getNode() 33 returns aailable node inde)
{ for( int p = 0; p B/ESGHI; p!! )
if(list[p].data == null) return p;
return "#;
)
public int find(6b7ect ob) 33 find the inde) (position) of the Ob0ect ob
{ int p = head;
(hile( p L= "#)
{ if( list[p].data == ob ) return p;
p = list[p].neFt; 33 adance to ne)t node
)
return "#;
)
public 6b7ect deleteFirst()
{ if( isImpt1() )
{ S1stem.out.println(,5ist is empt13 no deletion,);
return null;
)
6b7ect tmp = list[head].data;
if( list[head].neFt == "# ) 33 if the list contains one node,
head = "#; 33 ma%e list empty.
else
head = list[head].neFt;
count""; 33 update count
return tmp;
)
public 6b7ect deleteAfter(6b7ect F)
{ int p = find(F);
if( p == "# NN list[p].neFt == "# )
{ S1stem.out.println(,*o deletion,);
return null;
)
int M = list[p].neFt;
6b7ect tmp = list[M].data;
list[p].neFt = list[M].neFt;
count"";
return tmp;
)
public void display()
{ int p = head;
S1stem.out.print(,On5ist3 [ , );
(hile( p L= "#)
{ S1stem.out.print(list[p].data ! , ,); 33 print data
p = list[p].neFt; 33 adance to ne)t node
)
S1stem.out.println(,]On,);''
)
public boolean isEmpty()
{ if(count == 0) return true;
else return false;
public int size()
{ return count; )
)
class /rra15ist+emo
{
public static void main(String[] args)
{
/rra15ist lin@ed5ist = ne( /rra15ist(#0);
lin@ed5ist.initialiPe5ist();
lin@ed5ist.create5ist(:); 33 create 6 nodes
lin@ed5ist.displa1(); 33 print the list
S1stem.out.print(,GnsertKirst ;;3,);
lin@ed5ist.insertKirst(;;);
lin@ed5ist.displa1();
S1stem.out.print(,Gnsert ?? after ==3,);
lin@ed5ist.insert/fter(??, ==); 33 insert 77 after 88
lin@ed5ist.displa1();
6b7ect item = lin@ed5ist.deleteKirst(); S1stem.out.println(,+eleted node3 , ! item);
lin@ed5ist.displa1();
S1stem.out.print(,GnsertKirst <<3,);
lin@ed5ist.insertKirst(<<);
lin@ed5ist.displa1();
item = lin@ed5ist.delete/fter(>>); 33 delete node after node 99
S1stem.out.println(,+eleted node3 , ! item);
lin@ed5ist.displa1();
S1stem.out.println(,siPe()3 , ! lin@ed5ist.siPe());
)
)
The following output is generated by this program:
5ist3 [ ## >> == :: ]
GnsertKirst ;;3
5ist3 [ ;; ## >> == :: ]
Gnsert ?? after ==3
5ist3 [ ;; ## >> == ?? :: ]
+eleted node3 ;;
5ist3 [ ## >> == ?? :: ]
GnsertKirst <<3
5ist3 [ << ## >> == ?? :: ]
+eleted node3 ==
5ist3 [ << ## >> ?? :: ]
siPe()3 ;
Linked Implementation of List
LinkedList class implemented by List interface is gien 1rogram :7(d) and it is tested in 1rogram
class LinkedList implements List
{
class Node
{ 6b7ect data; 33 data item
*ode neFt; 33 refers to ne)t node in the list
*ode( 6b7ect d ) 33 constructor
{ data = d; ) 33 4neFtQ is automatically set to null
)
*ode head; 33 head refers to first node
*ode p; 33 p refers to current node
int count; 33 current number of nodes
public void createList(int n) 33 create ;n; nodes
{
p = ne( *ode(##); 33 create first node
head = p; 33 assign mem. address of ;p; to ;head;
for( int i = #; i n; i!! ) 33 create ;n"#; nodes
p = p.neFt = ne( *ode(## ! ##Ji);
count = n;
)
public void insertFirst(6b7ect item) 33 insert at the beginning of list
{
p = ne( *ode(item); 33 create new node
p.neFt = head; 33 new node refers to old head
head = p; 33 new head refers to new node
count!!;
)
public void insertAfter(6b7ect item,6b7ect @e1)
{
p = find(@e1); 33 get <location of %ey item=
if( p == null )
S1stem.out.println(@e1 ! , @e1 is not found,);
else
{ *ode M = ne( *ode(item); 33 create new node
M.neFt = p.neFt; 33 new node ne)t refers to p.ne)t
p.neFt = M; 33 p.ne)t refers to new node
count!!;
)
)
public *ode find(6b7ect @e1)
{
p = head;
(hile( p L= null ) 33 start at beginning of list until end of list
{
if( p.data == @e1 ) return p; 33 if found, return %ey
p = p.neFt; 33 moe to ne)t node
)
return null; 33 if %ey search is unsuccessful, return null
)
public 6b7ect deleteFirst() 33 delete first node
{
if( isImpt1() )
{ S1stem.out.println(,5ist is empt13 no deletion,);
return null;
)
*ode tmp = head; 33 tmp saes reference to head
head = tmp.neFt;
count"";
return tmp.data;
)
public 6b7ect deleteAfter(6b7ect @e1) 33 delete node after @e1 item
{ p = find(@e1); 33 p & <location of %ey node=
if( p == null )
{ S1stem.out.println(@e1 ! , @e1 is not found,);
return null;
)
if( p.neFt == null ) 33 if(there is no node after %ey node)
{ S1stem.out.println(,*o deletion,);
return null;
)
else
{ *ode tmp = p.neFt; 33 sae node after %ey node
p.neFt = tmp.neFt; 33 point to ne)t of node deleted
count"";
return tmp.data; 33 return deleted node
)
)
public void displayList()
{ p = head; 33 assign mem. address of ;head; to ;p;
S1stem.out.print(,On5in@ed 5ist3 ,);
(hile( p L= null ) 33 start at beginning of list until end of list
{ S1stem.out.print(p.data ! , "& ,); 33 print data
p = p.neFt; 33 moe to ne)t node
)
S1stem.out.println(p); 33 prints RnullR
)
public boolean isEmpty() 33 true if list is empty
{ return (head == null); )
public int siPe()
{ return count; )
) 33 end of Lin%eList class
class 5in@ed5ist+emo
{ public static void main(String[] args)
{ 5in@ed5ist list = ne( 5in@ed5ist(); 33 create list ob0ect
list.create5ist(:); 33 create 6 nodes
list.displa15ist();
list.insertKirst(;;); 33 insert >> as first node
list.displa15ist();
list.insert/fter(??, ==); 33 insert 77 after 88
list.displa15ist();
6b7ect item = list.deleteKirst(); 33 delete first node
if( item L= null )
{ S1stem.out.println(,deleteKirst()3 , ! item);
list.displa15ist();
)
item = list.delete/fter(>>); 33 delete a node after node(99)
if( item L= null )
{ S1stem.out.println(,delete/fter(>>)3 , ! item);
list.displa15ist();
)
S1stem.out.println(,siPe()3 , ! list.siPe());
)
)
?ere is the output from 5in@ed5ist+emo.7ava:
5in@ed 5ist3 ## "& >> "& == "& :: "& null
5in@ed 5ist3 ;; "& ## "& >> "& == "& :: "& null
5in@ed 5ist3 ;; "& ## "& >> "& == "& ?? "& :: "& null
deleteKirst()3 ;;
5in@ed 5ist3 ## "& >> "& == "& ?? "& :: "& null
delete/fter(>>)3 ==
5in@ed 5ist3 ## "& >> "& ?? "& :: "& null
si@e(): 6
%. Write Java programs to implement the follo"ing using an array.
(a) Stack ADT
(b) ueue ADT
Stack ADT
! Atac% is an !bstract -ata Type (!-T) that supports the following methods:
push(obj): !dd ob0ect obj at the top of the stac%.
Input: Ob0ect$ Output: /one.
obj pop(): -elete an item from the top of the stac% and returns ob0ect obj$ an error occurs if the stac% is empty.
Input: /one$ Output: Ob0ect.
obj peek(): 2eturns the top ob0ect obj on the stac% , without remoing it$ an error occurs if the stac% is empty.
Input: /one$ Output: Ob0ect.
boolean isEmpty(): 2eturns a boolean indicating if the stac% is empty.
Input: /one$ Output: boolean (true or false).
int size(): 2eturns the number of items on the stac%.
Input: /one$ Output: integer.
Type Ob0ect may be any type that can be stored in the stac%. The actual type of the ob0ect will be proided by the
user. The !-T is translated into a ,aa interface in 1rogram
Program: A Stack Inter!ace
public interfaceStack
{ public void push(6b7ect ob);
public 6b7ect pop();
public 6b7ect peek();
public boolean isEmpty();
public int size();
)
The push, pop, peek, empty, and size operations are translated directly into specifications for methods named push(),
pop(), pee@(), isImpt1(), and siPe() respectiely. These are conentional names for stac% operations. Bach
method is defined by specifying its return alue and any changes that it ma%es to the ob0ect.
Stack Im"#ementation
There are seeral ways to implement the Stac@ interface. The simplest is to use an ordinary array. This is done in
1rogram :C(b). The /rra1Stac@ implementation uses an array a[] to store elements of the stac%. *ts other data
field is the integer top, which refers top element of the stac%. The top is also used to count the current number of
items in the stac%.
Program (b): An ArrayStack $#ass
public class ArrayStack implements Stack
{
private 6b7ect a[];
private int top; 33 stac% top
public /rra1Stac@(int n) 33 constructor
{ a = ne( 6b7ect[n]; 33 create stac% array
top = "#; 33 no items in the stac%
)
public void push(6b7ect item) 33 add an item on top of stac%
{
if(top == a.length"#)
{ S1stem.out.println(,Stac@ is full,);
return;
)
top!!; 33 increment top
a[top] = item; 33 insert an item
)
public 6b7ect pop() 33 remoe an item from top of stac%
{
if( isImpt1() )
{ S1stem.out.println(,Stac@ is empt1,);
return null;
)
6b7ect item = a[top]; 33 access top item
top""; 33 decrement top
return item;
)
public 6b7ect peek() 33 get top item of stac%
{ if( isImpt1() ) return null;
return a[top];
)
public boolean isEmpty() 33 true if stac% is empty
{ return (top == "#); )
public int size() 33 returns number of items in the stac%
{ return top!#; )
)
The constructor creates a new stac% of a si@e, n specified in its argument. The ariable top stores the inde) of the
item on the top of the stac%.
The push() method increments top so it points to the space 0ust aboe the preious top, and stores a data item
there. /otice that top is incremented before the item is inserted. The pop() method returns the alue at top and
then decrements top. This effectiely remoes the item from the stac%$ it is inaccessible, although the alue remains
in the array (until another item is pushed into the cell). The pee@() method simply returns the alue at top, without
changing the stac%. The specifications for the pop() and pee@() methods in the Stac@ interface require that the
stac% be not empty. The isImpt1() method returns true if the stac% is empty. The top ariable is at S# if the stac%
is empty.
The /rra1Stac@ class is tested in the 1rogram
Program : Testing ArrayStack $#ass
class /rra1Stac@+emo
{
public static void main(String[] args)
{
/rra1Stac@ st@ = ne( /rra1Stac@(:); 33 create stac% of si@e 6
6b7ect item;
st@.push(R/R); 33 push 8 items onto stac%
st@.push(R2R);
st@.push(R$R);
S1stem.out.println(,siPe()3 ,! st@.siPe());
item = st@.pop(); 33 delete item
S1stem.out.println(item ! , is deleted,);
st@.push(R+R); 33 add three more items to the stac%
st@.push(RIR);
st@.push(RKR);
S1stem.out.println(st@.pop() ! , is deleted,);
st@.push(RTR); 33 push one item
item = st@.pee@(); 33 get top item from the stac%
S1stem.out.println(item ! , is on top of stac@,);
)
)
Output of this program is:
siPe()3 =
$ is deleted
Stac@ is full
I is deleted
T is on top of stac@
ueue ADT
The elements in a queue are of generic type Ob0ect. The queue elements are linearly ordered from the front to the
rear. Blements are inserted at the rear of the queue (enqueued) and are remoed from the front of the queue
(dequeued). ! Dueue is an !bstract -ata Type (!-T) that supports the following methods:
insert(obj): !dds ob0ect obj at the rear of a queue.
Input: Ob0ect$ Output: /one.
obj remove(): -eletes an item from the front of a queue and returns ob0ect obj$ an error occurs if the queue is empty.
Input: /one$ Output: Ob0ect.
obj peek(): 2eturns the ob0ect obj at the front of a queue , without remoing it$ an error occurs if the queue is empty.
Input: /one$ Output: Ob0ect.
boolean isEmpty(): 2eturns a boolean indicating if the queue is empty.
Input: /one$ Output: boolean (true or false).
int size(): 2eturns the number of items in the queue.
Input: /one$ Output: integer.
Type Ob0ect may be any type that can be stored in the queue. The actual type of the ob0ect will be proided by the
user. The !-T is translated into a ,aa interface in 1rogram
Program : A ueue Inter!ace
public interface ueue
{
public void insert(6b7ect ob);
public 6b7ect remove();
public 6b7ect peek();
public boolean isEmpty();
public int size();
)
/ote the similarities between these specifications and that of the stac% interface. The only real difference, between the
names of the operations, is that the queue adds new elements at the opposite end from which they are accessed, while
the stac% adds them at the same end.
ueue Im"#ementation
The /rra1Uueue implementation of Mueue interface is done by ta%ing an array, que'n( and treating it as if it were
circular. The elements are inserted by increasing rear to the ne)t free position. +hen rear & nE:, the ne)t element is
entered at que'#( in case that spot is free. That is, the element que'nE:( follows que'#(. 1rogram :C(e) implements the
/rra1Uueue class, and 1rogram :C(f) tests this class.
Program : An Arrayueue $#ass
class Arrayueue implements ueue
{ private int maFSiPe; 33 ma)imum queue si@e
private 6b7ect[] Mue; 33 que is an array
private int front;
private int rear;
private int count; 33 count of items in queue (queue si@e)
public /rra1Uueue(int s) 33 constructor
{ maFSiPe = s;
Mue = ne( 6b7ect[maFSiPe];
front = rear = "#;
count = 0;
)
public void insert(6b7ect item) 33 add item at rear of queue
{
if( count == maFSiPe )
{ S1stem.out.println(,Uueue is Kull,); return; )
if(rear == maFSiPe"# NN rear == "#)
{ Mue[0] = item;
rear = 0;
if( front == "#) front = 0;
)
else Mue[!!rear] = item;
count!!; 33 update queue si@e
)
public 6b7ect remove() 33 delete item from front of queue
{
if( isImpt1() )
{S1stem.out.println(,Uueue is Impt1,); return 0; )
6b7ect tmp = Mue[front]; 33 sae item to be deleted
Mue[front] = null; 33 ma%e deleted item5s cell empty
if( front == rear )
rear = front = "#;
else if( front == maFSiPe"# ) front = 0;
else front!!;
count""; 33 less one item from the queue si@e
return tmp;
)
public 6b7ect peek() 33 pee% at front of the queue
{ return Mue[front]; )
public boolean isEmpty() 33 true if the queue is empty
{ return (count == 0); )
public int size() 33 current number of items in the queue
{ return count; )
public void displayAll()
{
S1stem.out.print(,Uueue3 ,);
for( int i = 0; i maFSiPe; i!! )
S1stem.out.print( Mue[i] ! , ,);
S1stem.out.println();
)
)
Program %&(!): Testing Arrayueue c#ass
class ueueDemo
{
public static void main(String[] args)
{
3F queue holds a ma) of > items F3
/rra1Uueue M = ne( /rra1Uueue(;);
6b7ect item;
M.insert(R/R); M.insert(R2R); M.insert(R$R); M.displa1/ll();
item = M.remove(); 33 delete item
S1stem.out.println(item ! , is deleted,);
item = M.remove();
S1stem.out.println(item ! , is deleted,);
M.displa1/ll();
M.insert(R+R); 33 insert 8 more items
M.insert(RIR);
M.insert(RKR);
M.displa1/ll();
item = M.remove();
S1stem.out.println(item ! , is deleted,);
M.displa1/ll();
S1stem.out.println(,pee@()3 , ! M.pee@());
M.insert(RTR);
M.displa1/ll();
S1stem.out.println(,Uueue siPe3 , !
M.siPe());
)
)
Output of this program is as follows:
Uueue3 / 2 $ null null
/ is deleted
2 is deleted
Uueue3 null null $ null null
Uueue3 K null $ + I
$ is deleted
Uueue3 K null null + I
pee@()3 +
Uueue3 K T null + I
Uueue siPe3 :
>. +rite a ,aa program that uses both stac% and queue to test whether the gien string is a palindrome.
Testing whether the given string is a palindrome using stack
import 7ava.util.Stac@;
class !alindrome
G
public static void main(String args[])
{
String str = ,B/5/V/5/B,;
if( is0alindrome(str) )
S1stem.out.println( str ! , is a 0alindrome,);
else
S1stem.out.println( str ! , is not a 0alindrome,);
)
static boolean is0alindrome(String str)
{
Stac@$haracter& st@ = ne( Stac@$haracter&();
for( int i=0; i str.length(); i!! )
st@.push(str.char/t(i));
for( int i=0; i str.length()'>; i!! )
if( str.char/t(i) L= st@.pop() ) return false;
return true;
)
)
Testing whether the given string is a palindrome using ueue
import 7ava.util.5in@ed5ist;
class !alindrome
{
public static void main(String args[])
{
String str = ,-/+/-,;
if( is0alindrome(str) )
S1stem.out.println( str ! , is a 0alindrome,);
else
S1stem.out.println( str ! , is not a 0alindrome,);
)
static boolean is0alindrome(String str)
{
5in@ed5ist$haracter& Mue = ne( 5in@ed5ist$haracter&();
int n = str.length();
for( int i=0; i n; i!! )
Mue.add5ast(str.char/t(i));
for( int i=n"#; i & n'>; i"" )
if( str.char/t(i) L= Mue.removeKirst() ) return false;
return true;
)
)
?. Write Java programs to implement the follo"ing using a singly lin&ed list.
(a) Stac& '()
(b) *ueue '()
Linked Implementation o! a "tack
class Node
{ int data; 33 data item
*ode neFt; 33 ne)t node in lin%edEstac%
*ode( int d ) 33 constructor
{ data = d; ) 33 ne)t is automatically set to null
)
class LinkedStack
{
*ode top; 33 top refers to topEnode
*ode p; 33 p refers to current node
public void push(int item) 33 add item onto stac%
{
p = ne( *ode(item); 33 create new node
p.neFt = top; 33 new node refers to old top
top = p; 33 top refers to new node
)
public *ode pop() 33 remoe a node from the stac%
{
if( isImpt1() )
{ S1stem.out.println(,Stac@ is empt1,);
return null;
)
*ode tmp = top; 33 tmp saes reference to top node
top = tmp.neFt; 33 now, top refers to ne)t node of old top
return tmp; 33 return the popped item
)
public *ode peek() 33 get top node from the stac%, without deleting
{
if( isImpt1() )
{ S1stem.out.println(,Stac@ is empt1,);
return null;
)
return top;
)
public void displayStack()
{
p = top; 33 p refers to top
S1stem.out.print(,On$ontents of Stac@3 [ ,);
(hile( p L= null ) 33 start printing from top of stac% to bottom of stac%
{
S1stem.out.print(p.data ! , ,); 33 print data
p = p.neFt; 33 moe to ne)t node
)
S1stem.out.println(,],);
)
public boolean isEmpty() 33 true if stac% is empty
{ return (top == null); )
)
''''''''''''''''''''''''' LinkedStackDemo.java '''''''''''''''''
class LinkedStackDemo
{
public static void main(String[] args)
{
5in@edStac@ st@ = ne( 5in@edStac@(); 33 create stac% ob0ect
*ode item; 33 item stores popped node
st@.push(>0); 33 add 9#, 8>, 6# to stac%
st@.push(=;);
st@.push(:0);
st@.displa1Stac@(); 33 print contents of stac%
item = st@.pop(); 33 remoe a node from the top and print it
if( item L= null )
{
S1stem.out.println(,0opped item3 , ! item.data);
st@.displa1Stac@();
)
st@.push(?;); 33 insert 7>, C#, C>
st@.push(<0);
st@.push(<;);
st@.displa1Stac@(); 33 display contents of stac%
item = st@.pop(); 33 remoe a node from the top and display it
if( item L= null )
{
S1stem.out.println(W0opped item3 X ! item.data);
st@.displa1Stac@();
)
S1stem.out.println(Wpee@()3 X ! st@.pee@());33 get top item
st@.push(90); 33 insert H#
st@.displa1Stac@();
)
)
Output from 5in@edStac@ operations program:
$ontents of Stac@3 [ :0 =; >0 ]
0opped item3 :0
$ontents of Stac@3 [ =; >0 ]
$ontents of Stac@3 [ <; <0 ?; =; >0 ]
0opped item3 <;
pee@()3 <0
$ontents of Stac@3 [ <0 ?; =; >0 ]
$ontents of Stac@3 [ 90 <0 ?; =; >0 ]
# Linkedueue $lass
public class Linkedueue
{
class Node
{ 6b7ect data;
*ode neFt;
*ode(6b7ect item) 33 constructor
{ data = item; )
)
*ode front, rear;
int count;
public void insert(6b7ect item)
{
*ode p = ne( *ode(item);
if(front == null) 33 queue is empty$ insert first item
{ front = rear = p;
rear.neFt = null;
)
if(front == rear) 33 queue contains one item$ insert second item
{ rear = p;
front.neFt = rear;
rear.neFt = null;
)
else 33 queue contains 9 or more items
{ rear.neFt = p; 33 old rear.neFt refers to p
rear = p; 33 new rear refers to p
rear.neFt = null;
)
count!!; 33 increment queue si@e
)
public 6b7ect remove()
{ if(isImpt1())
{ S1stem.out.println(,U is empt1,); return null; )
6b7ect item = front.data;
front = front.neFt;
count""; 33 decrement queue si@e
return item;
)
public boolean isEmpty()
{ return (front == null); )
public 6b7ect peek()
{ return front.data; )
public int size()
{ return count; )
public void display()
{ *ode p = front;
S1stem.out.print(,5in@ed U3 ,);
if(p == null) S1stem.out.println(,empt1,);
(hile( p L= null )
{
S1stem.out.print(p.data ! , ,);
p = p.neFt;
)
S1stem.out.println();
)
)
Testing Linkedueue $lass
class LinkedueueDemo
{ public static void main(String[] args)
{
5in@edUueue M = ne( 5in@edUueue();
M.displa1();
M.insert(R/R);
M.insert(R2R);
M.insert(R$R);
M.insert(R+R);
M.displa1();
S1stem.out.println(,delete()3 , ! M.remove());
M.displa1();
S1stem.out.println(,pee@()3 , ! M.pee@());
M.insert(RIR);
M.insert(RKR);
S1stem.out.println(,delete()3 , ! M.remove());
M.displa1();
S1stem.out.println(,siPe()3 , ! M.siPe());
)
)
?ere is the output of this program:
5in@ed U3 empt1
5in@ed U3 / 2 $ +
remove()3 /
5in@ed U3 2 $ +
pee@()3 2
remove()3 2
<. 5in@ed U3 $ + I K
siPe()3 :
Write Java programs for implementing the follo"ing sorting methods:
(a) $ubble sort
(b) Selection sort
(c) *uic& sort
Bu%%le "ort
void bubbleSort(6b7ect[] a)
{
int i, pass, eFch, n = a.length;
6b7ect tmp;
for( pass = 0; pass n; pass!! )
G e)ch & #
for( i & #$ i " nEpassE:$ iII ) if( ((.omparable)a'i().compareTo(a'iI:() J #)
{ tmp = a[i];
a[i] = a[i!#];
a[i!#] = tmp;
eFch!!;
)
if( eFch == 0 ) return; 33 sorting finished K return early
)
}
)race of $ubble sort (elements
to be interchanged are sho"n
in re' colour) pass ( % 2 ) * + , &
Proce
ss
E 9C &' () 8C :> C> 78 7> Origi
nal
array
: 9C 8> &' (* :> C> 78 7> 6H, 8>
interc
hange
d
: 9C 8> 8C &' +) C> 78 7> 6H, 8C
interc
hange
d
: 9C 8> 8C :> 6H *) ,( 7> 6H, :>
interc
hange
d
: 9C 8> 8C :> 6H 78 *) ,) C>, 78
interc
hange
d
: 9C 8> (* +) 6H 78 7> C> C>, 7>
interc
hange
d
9 9C () +) 8C 6H 78 7> C> 8C, :>
interc
hange
d
8 2* +) 8> 8C 6H 78 7> C> 8>, :>
interc
hange
d
6 :> 9C 8> 8C 6H 78 7> C> 9C, :>
interc
hange
d
"election "ort
)race of Selection sort (elements to be
interchanged are sho"n in re' colour) (
% 2 ) * + , &
pass min a-pass. a-min. swap
a-pass./
a-min.
&' 9C 7> 8C +) C> 78 7# # 6 6H :> 6H, :>
:> 9C 7> 8C 6H C> 78 7# : : 9C 9C min & pass
no e)change
:> 9C ,) (* 6H C> 78 7# 9 8 7> 8C 7>, 8C
:> 9C 8C ,) &' C> 78 7# 8 6 7> 6H 7>, 6H
:> 9C 8C 6H ,) C> 78 ,0 6 C 7> 7# 7>, 7#
:> 9C 8C 6H 7# *) ,( 7> > 7 C> 78 C>, 78
:> 9C 8C 6H 7# 78 *) ,) 7 C C> 7> C>, 7>
:> 9C 8C 6H 7# 78 7> C> Aorted list
"election "ort
class SelectionSort+emo
{
public static void main(String[] args)
{
int[] arr = { :9, ><, ?;, =<, #;, <;, ?=, ?0 );
S1stem.out.print(,On 4nsorted arra13 ,);
displa1( arr );
selectionSort( arr );
S1stem.out.print(,On Sorted arra13 ,);
displa1( arr );
)
static void selectionSort( int a[] )
{
int n = a.length;
for( int pass = 0; pass n"#; pass!! )
{
int min = pass;
for( int i = pass!#; i n; i!! )
if( a[i] a[min] ) min = i;
if( min L= pass )
{
int tmp = a[min];
a[min] = a[pass];
a[pass] = tmp;
)
)
)
static void displa1( int a[] )
{
for( int i = 0; i a.length; i!! )
S1stem.out.print( a[i] ! , , );
)
)
1ollowing output is generated !rom this program:
4nsorted arra13 :9 >< ?; =< #; <; ?= ?0
Aorted array: :> 9C 8C 6H 7# 78 7> C>
2uick "ort
class Uuic@Sort+emo
{
public static void main(String[] args)
{
int[] arr = { ?;, =;, #;, 90, <;, :;,:0, ?0, 9;, >;, 8;, ;; );
S1stem.out.print(,On 4nsorted arra13 ,);
displa1( arr );
Muic@Sort( arr, 0, arr.length"# );
S1stem.out.print(,On Sorted arra13 ,);
displa1( arr );
)
static void "uickSort(int a[], int left, int right)
{
int ne(left = left, ne(right = right;
int amid, tmp;
amid = a[(left ! right)'>]; 33 piot is amid
do 33 doEwhileEloop
{
(hile( (a[ne(left] amid) YY (ne(left right))
ne(left!!;
(hile( (amid a[ne(right]) YY (ne(right & left))
ne(right"";
if(ne(left = ne(right)
{ tmp = a[ne(left];
a[ne(left] = a[ne(right];
a[ne(right] = tmp;
ne(left!!; ne(right"";
)
) (hile(ne(left = ne(right); 33 end of doEwhileEloop
if(left ne(right) Muic@Sort(a, left, ne(right);
if(ne(left right) Muic@Sort(a, ne(left, right);
)
static void displa1( int a[] )
{
for( int i = 0; i a.length; i!! )
S1stem.out.print( a[i] ! , , );
)
}
3utput:
4nsorted arra13 ?; =; #; 90 <; :; :0 ?0 9; >; 8; ;;
Sorted arra13 #; >; =; :0 :; ;; ?0 ?; <; 8; 90 9;
)race of *uic& sort
step a0 a+ a2 a( a& a) a, a* a4 a' a+0 a++ lef
t
ri
gh
t
piv
ot
# 7> 8> :> H# C> &) 6# 7# H> 9> L> >> # :: &)
: 9> 8> +) 6# 45 C> H# 7# H> 7> L> >> # 6 +)
9 15 8> 2) 6# 45 C> H# 7# H> 7> L> >> : 6 2)
8 15 25 8> &0 45 C> H# 7# H> 7> L> >> 9 6 &0
6 15 25 35 4 45 C> H# 7# ') 7> L> >> > :: ')
> 15 25 35 4 45 C> H# ,0 >> 7> L> !5 > :# ,0
7 15 25 35 4 45 )) " H# C> 7> L> !5 > 7 ))
C 15 25 35 4 45 55 " H# *) 7> L> !5 C :# *)
L 15 25 35 4 45 55 " "5 #5 '0 L> !5 H :# '0
H 15 25 35 4 45 55 " "5 #5 $5 ! !5 sorted array

You might also like