Created
May 16, 2023 02:34
-
-
Save leandromoh/209f164535f42cd7760c711191776349 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
var values = GenerateRandomNumber(200); | |
foreach(var x in MergeSort(values)) | |
Console.WriteLine(x); | |
static int[] GenerateRandomNumber(int size) | |
{ | |
var array = new int[size]; | |
var rand = new Random(); | |
var maxNum = 10000; | |
for (int i = 0; i < size; i++) | |
array[i] = rand.Next(maxNum + 1); | |
return array; | |
} | |
IEnumerable<int> MergeSort(IEnumerable<int> source) | |
{ | |
var a = new List<int>(); | |
var b = new List<int>(); | |
var x = false; | |
foreach(var item in source) | |
{ | |
x = !x; | |
if (x) | |
a.Add(item); | |
else | |
b.Add(item); | |
} | |
var totalSize = a.Count + b.Count; | |
var result = totalSize switch | |
{ | |
0 => Enumerable.Empty<int>(), | |
1 => a.Count == 1 ? a : b, | |
_ => Merge(MergeSort(a), MergeSort(b)) | |
}; | |
return result; | |
} | |
IEnumerable<int> Merge(IEnumerable<int> a, IEnumerable<int> b) | |
{ | |
a.TryGetNonEnumeratedCount(out var sizeA); | |
b.TryGetNonEnumeratedCount(out var sizeB); | |
var result = new List<int>(sizeA + sizeB); | |
using var ae = a.GetEnumerator(); | |
using var be = b.GetEnumerator(); | |
var af = ae.MoveNext(); | |
var bf = be.MoveNext(); | |
while(af && bf) | |
{ | |
if (ae.Current <= be.Current) | |
{ | |
result.Add(ae.Current); | |
af = ae.MoveNext(); | |
} | |
else | |
{ | |
result.Add(be.Current); | |
bf = be.MoveNext(); | |
} | |
} | |
if (af) | |
do | |
result.Add(ae.Current); | |
while(ae.MoveNext()); | |
if (bf) | |
do | |
result.Add(be.Current); | |
while(be.MoveNext()); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment