-
Notifications
You must be signed in to change notification settings - Fork 7
/
OrderedList.java
101 lines (95 loc) · 1.52 KB
/
OrderedList.java
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
package list;
public class OrderedList<D> implements List<D>
{
Integer buffer, size;
Object arr[];
public OrderedList()
{
buffer=5;
size=0;
arr=new Object[buffer];
}
public void add(D m)
{
Integer pos=-1;
for (Integer i=0; i<size; i++)
{
if((Integer)m<(Integer)arr[i])
{
pos=i;
break;
}
}
if(pos!=-1)
{
for(Integer i=size; i>pos; i--)
arr[i]=arr[i-1];
arr[pos]=m;
}
else
arr[size]=m;
size++;
if(size==buffer)
{
Object arr2[];
arr2=new Object[buffer*2];
buffer*=2;
for(Integer i=0; i<size; i++)
arr2[i]=arr[i];
arr=arr2;
}
}
public void traverse()
{
for(Integer i=0;i<size;i++)
{
System.out.print(arr[i]+ " ");
}
System.out.println();
}
public void remove(D m)
{
Integer pos=search(m);
for(Integer i=pos;i<size;i++)
{
arr[i]=arr[i+1];
}
size--;
}
public Integer search(D m)
{
Integer hi,lo,mid;
hi=size-1;
lo=0;
while(hi>lo)
{
mid=(hi+lo)/2;
if((Integer)m==(Integer)arr[mid])
return mid;
else if((Integer)m>(Integer)arr[mid])
lo=mid;
else if((Integer)m<(Integer)arr[mid])
hi=mid;
}
System.out.println("element not found");
return -1;
}
public void checkIndex(Integer pos)
{
Integer size=getSize();
if(pos<0||pos>size)
{
throw new IndexOutOfBoundsException("index = "+pos+"\nsize = "+size+"\n");
}
else System.out.println("index position found");
}
public Integer getSize()
{
return size;
}
public D get(Integer pos)
{
checkIndex(pos);
return (D)arr[pos];
}
}