-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenericList.cs
140 lines (119 loc) · 3.36 KB
/
GenericList.cs
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
namespace GenericClass
{
using System;
using System.Collections.Generic;
using System.Text;
public class GenericList<T> where T : IComparable<T>
{
private T[] data;
private int nextPosition;
public GenericList(int initialCapacity)
{
this.data = new T[initialCapacity];
}
public void Add(T elemnt)
{
if (this.data.Length == this.nextPosition)
{
this.AutoGrow();
}
this.data[nextPosition] = elemnt;
this.nextPosition++;
}
public T this[int index]
{
get
{
if (index > this.nextPosition - 1)
{
throw new IndexOutOfRangeException();
}
return this.data[index];
}
private set
{
this.data[index] = value;
}
}
public void Remuve(int index)
{
for (int i = index; i < nextPosition && i < (this.data.Length - 1); i++)
{
this.data[i] = this.data[i + 1];
}
this.nextPosition--;
this.data[nextPosition] = default(T);
}
public void Insert(int index, T element)
{
if (this.data.Length == this.nextPosition)
{
this.AutoGrow();
}
for (int i = this.nextPosition; i >= index && i > 0; i--)
{
this.data[i] = this.data[i - 1];
}
this.data[index] = element;
this.nextPosition++;
}
public void Clear()
{
this.data = new T[this.data.Length];
}
public T Min()
{
if (this.nextPosition == 0)
{
throw new ArgumentException("There ara no element!");
}
T min = this.data[0];
foreach (T item in data)
{
if (min.CompareTo(item) > 0)
{
min = item;
}
}
return min;
}
public T Max()
{
if (this.nextPosition == 0)
{
throw new ArgumentException("There ara no element!");
}
T max = this.data[0];
foreach (T item in data)
{
if (max.CompareTo(item) < 0)
{
max = item;
}
}
return max;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.nextPosition; i++)
{
sb.Append(this.data[i]);
if (i < this.nextPosition - 1)
{
sb.Append(", ");
}
}
return sb.ToString();
}
private void AutoGrow()
{
var newData = new T[this.data.Length * 2];
for (int i = 0; i < this.data.Length; i++)
{
newData[i] = this.data[i];
}
this.data = newData;
}
}
}