- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathInsertionSorter.cs
64 lines (54 loc) · 1.89 KB
/
InsertionSorter.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
usingSystem.Collections.Generic;
usingDataStructures.Lists;
namespaceAlgorithms.Sorting
{
/// <summary>
/// Implements this Insertion Sort algorithm over ArrayLists.
/// </summary>
publicstaticclassInsertionSorter
{
//
// The quick insertion sort algorithm.
// For any collection that implements the IList interface.
publicstaticvoidInsertionSort<T>(thisIList<T>list,Comparer<T>comparer=null)
{
//
// If the comparer is Null, then initialize it using a default typed comparer
comparer=comparer??Comparer<T>.Default;
// Do sorting if list is not empty.
inti,j;
for(i=1;i<list.Count;i++)
{
Tvalue=list[i];
j=i-1;
while((j>=0)&&(comparer.Compare(list[j],value)>0))
{
list[j+1]=list[j];
j--;
}
list[j+1]=value;
}
}
//
// The quick insertion sort algorithm.
// For the internal ArrayList<T>. Check the DataStructures.ArrayList.cs.
publicstaticvoidInsertionSort<T>(thisArrayList<T>list,Comparer<T>comparer=null)
{
//
// If the comparer is Null, then initialize it using a default typed comparer
comparer=comparer??Comparer<T>.Default;
for(inti=1;i<list.Count;i++)
{
for(intj=i;j>0;j--)
{
if(comparer.Compare(list[j],list[j-1])<0)//(j)th is less than (j-1)th
{
vartemp=list[j-1];
list[j-1]=list[j];
list[j]=temp;
}
}
}
}
}
}