-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinSearch.java
More file actions
118 lines (109 loc) · 2.77 KB
/
BinSearch.java
File metadata and controls
118 lines (109 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import java.util.*;
class BinSearch
{
Node front, rear;
BinSearch()
{
front = null;
rear = null;
}
void Insert(int n)
{
Node N = new Node(n);
if (front == null)
{
front = N;
rear = front;
}
else
{
rear.next = N;
rear = rear.next;
}
}
void Display()
{
if (front == null)
System.out.print("List empty");
Node ptr = front;
while (ptr != null)
{
System.out.print(ptr.n + "\t");
ptr = ptr.next;
}
System.out.println();
}
Node middleNode(Node start, Node end)
{
if (start == null)
return null;
Node slow = start;
Node fast = start.next;
while (fast != end)
{
if (fast != end)
{
slow = slow.next;
fast = fast.next;
}
if (fast != end)
fast = fast.next;
}
return slow;
}
Node Search(int value)
{
Node start = front;
Node end = null;
do
{
Node m = middleNode(start, end);
if (m == null)
return null;
if (m.n == value)
return m;
if (m.n < value)
start = m.next;
if (m.n > value)
end = m;
} while (end == null || end != start);
return null;
}
public static void main()
{
Scanner sc = new Scanner(System.in);
BinSearch L = new BinSearch();
System.out.println("1. Insert\n 2. Search\n 3. Display\n 4. Quit");
int ch;
do
{
System.out.println("Make choice:");
ch = sc.nextInt();
switch (ch)
{
case 1:
System.out.println("Enter item:");
int x = sc.nextInt();
L.Insert(x);
break;
case 2:
System.out.println("Enter search item:");
int a = sc.nextInt();
Node N = L.Search(a);
if (N == null)
System.out.println("Element not found");
else
System.out.println("Element found in list");
break;
case 3:
L.Display();
break;
case 4:
System.out.println("Quitting program");
break;
default:
System.out.println("Invalid: Choose again");
}
}while (ch != 4);
}
}