Skip to content

Instantly share code, notes, and snippets.

@HallexCosta
Last active March 22, 2021 19:10
Show Gist options
  • Save HallexCosta/739a4d5b38591ae84212d116f85e713d to your computer and use it in GitHub Desktop.
Save HallexCosta/739a4d5b38591ae84212d116f85e713d to your computer and use it in GitHub Desktop.
MergeSort with C#
public class Merge {
public static int[] data;
public static void sort(int[] a, int lb, int ub) {
if (lb < ub) {
int mid = (lb + ub) / 2;
Merge.sort(a, lb, mid);
Merge.sort(a, mid + 1, ub);
Merge.concat(a, lb, mid, ub);
}
}
private static void concat(int[] a, int lb, int mid, int ub) {
int i = lb;
int j = mid + 1;
int k = lb;
int[] b = new int[a.Length];
while (i <= mid && j <= ub) {
if (a[i] <= a[j]) {
b[k] = a[i++];
} else {
b[k] = a[j++];
}
k++;
}
if (i > mid) {
while (j <= ub) {
b[k++] = a[j++];
}
} else {
while (i <= mid) {
b[k++] = a[i++];
}
}
for (k = lb; k <= ub; k++) {
a[k] = b[k];
}
Merge.data = new int[a.Length];
Merge.data = a;
}
public static void display(int[] a) {
Console.WriteLine(Merge.join(", ", a, "[", "]"));
Console.WriteLine($"Tamanho: {a.Length}");
Console.WriteLine();
}
private static string join(string separator, int[] pieces, string start = "", string end = "") {
string text = start;
for (int k = 0; k < pieces.Length; k++) {
string piece = pieces[k].ToString();
if (k == pieces.Length - 1) {
separator = "";
}
text += $"{piece}{separator}";
}
text += end;
return text;
}
}
public class Program
{
public static void Main(string[] args)
{
int[] a = new int[9]{15, 5, 24, 8, 1, 3, 16, 10, 20};
Merge.display(a); // output: [15, 5, 24, 8, 1, 3, 16, 10, 20]
Merge.sort(a, 0, a.Length - 1);
Merge.display(a); // output: [1, 3, 5, 8, 10, 15, 16, 20, 24]
}
}
@HallexCosta
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment