Created
February 9, 2014 05:47
-
-
Save rossmurray/8894908 to your computer and use it in GitHub Desktop.
merge and insertion for an assignment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var r = new Random(100); | |
var list = Enumerable.Range(1,1000000).OrderBy(x => r.Next()).ToList(); | |
var sorted = MergeSort(list); | |
var correct = (sorted.SequenceEqual(list.OrderBy(x => x))); //true | |
} | |
public IList<int> MergeSort(IEnumerable<int> source) | |
{ | |
var length = source.Count(); | |
if(length <= 8) return InsertionSort(source.ToList()); | |
var interval = length / 3; | |
var left = source.Take(interval).ToList(); | |
var middle = source.Skip(interval).Take(interval).ToList(); | |
var right = source.Skip(interval).Skip(interval).ToList(); | |
var leftSorted = MergeSort(left); | |
var midSorted = MergeSort(middle); | |
var rightSorted = MergeSort(right); | |
var merged = Merge(leftSorted, midSorted); | |
var result = Merge(merged, rightSorted); | |
return result; | |
} | |
private IList<int> Merge(IList<int> left, IList<int> right) | |
{ | |
var leftCount = left.Count; | |
var rightCount = right.Count; | |
var length = leftCount + rightCount; | |
var result = new int[length]; | |
var ai = 0; | |
var bi = 0; | |
for (int i = 0; i < length; i++) | |
{ | |
var a = ai >= leftCount ? int.MaxValue : left[ai]; | |
var b = bi >= rightCount ? int.MaxValue : right[bi]; | |
if(a < b) | |
{ | |
result[i] = a; | |
ai++; | |
} | |
else | |
{ | |
result[i] = b; | |
bi++; | |
} | |
} | |
return result; | |
} | |
public IList<int> InsertionSort(IList<int> source) | |
{ | |
var result = new List<int>(); | |
var count = source.Count(); | |
for (int i = 0; i < count; i++) | |
{ | |
var destination = FindFirstGreater(source, source[i], i); | |
MoveDownTo(source, i, destination); | |
} | |
return source; | |
} | |
private int FindFirstGreater(IList<int> source, int element, int max) | |
{ | |
var found = max; | |
for (int i = max - 1; i >= 0; i--) | |
{ | |
if(source[i] > element) found = i; | |
else return found; | |
} | |
return found; | |
} | |
private void MoveDownTo(IList<int> collection, int sourceIndex, int destinationIndex) | |
{ | |
if(sourceIndex == destinationIndex) return; | |
var n = collection[sourceIndex]; | |
for (int i = sourceIndex; i > destinationIndex; i--) | |
{ | |
collection[i] = collection[i-1]; | |
} | |
collection[destinationIndex] = n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment