Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace _13MergeSort
- {
- class MergeSort
- {
- static void Main()
- {
- int length;
- bool correct;
- do
- {
- Console.WriteLine("Please input the length of the array");
- correct = int.TryParse(Console.ReadLine(), out length) && length > 0;
- if (!correct)
- {
- Console.WriteLine("This is not a correct number!");
- }
- } while (!correct);
- int[] array = new int[length];
- Console.WriteLine("Please input the integer numbers of the array.");
- for (int i = 0; i < length; i++)
- {
- array[i] = int.Parse(Console.ReadLine());
- }
- Console.WriteLine("The array is:");
- Console.WriteLine(String.Join(", ", array));
- array = Sort(array);
- Console.WriteLine("The sorted array is:");
- Console.WriteLine(String.Join(", ", array));
- }
- static int[] Sort(int[] array)
- {
- if (array.Length < 2)
- {
- return array;
- }
- int middle = array.Length / 2;
- int[] left = new int[middle];
- for (int i = 0; i < left.Length; i++)
- {
- left[i] = array[i];
- }
- int[] right = new int[array.Length - middle];
- for (int i = 0; i < right.Length; i++)
- {
- right[i] = array[middle + i];
- }
- Sort(left);
- Sort(right);
- int leftIndex = 0;
- int rightIndex = 0;
- for (int i = 0; i < array.Length; i++)
- {
- if (leftIndex < left.Length && rightIndex < right.Length)
- {
- if (left[leftIndex] <= right[rightIndex])
- {
- array[i] = left[leftIndex];
- leftIndex++;
- }
- else
- {
- array[i] = right[rightIndex];
- rightIndex++;
- }
- }
- else if (leftIndex == left.Length)
- {
- array[i] = right[rightIndex];
- rightIndex++;
- }
- else
- {
- array[i] = left[leftIndex];
- leftIndex++;
- }
- }
- return array;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement