InsertSorted

Insert an item to a sorted List

源代码:

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
static class Extensions {

public static int InsertSorted<T>(this IList<T> source, T value) where T : IComparable<T> {
if (source is null) {
throw new ArgumentNullException(nameof(source));
}
for (int i = 0; i < source.Count; i++) {
if (value.CompareTo(source[i]) < 0) {
source.Insert(i, value);
return i;
}
}
source.Add(value);
return source.Count - 1;
}

public static int InsertSorted<T>(this IList<T> source, T value, IComparer<T> comparison) {
if (source is null) {
throw new ArgumentNullException(nameof(source));
}
for (int i = 0; i < source.Count; i++) {
if (comparison.Compare(value, source[i]) < 0) {
source.Insert(i, value);
return i;
}
}
source.Add(value);
return source.Count - 1;
}

public static int InsertSorted<T>(this IList<T> source, T value, Comparison<T> comparison) {
if (source is null) {
throw new ArgumentNullException(nameof(source));
}
for (int i = 0; i < source.Count; i++) {
if (comparison(value, source[i]) < 0) {
source.Insert(i, value);
return i;
}
}
source.Add(value);
return source.Count - 1;
}
}

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var l = new List<int>() {
1,2,4,8,5,
};

l.Sort();

l.InsertSorted(0);
l.InsertSorted(6);
l.InsertSorted(9);
l.InsertSorted(3, Comparer<int>.Default);
l.InsertSorted(7, (x, y) => x.CompareTo(y));

foreach (var item in l) {
Console.WriteLine(item);
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×