Write C functions to sort a set of integers in descending order using top-down approach of merge sort code example
Example 1: merge sort c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Merge_sort
{
class Program
{
static void Main(string[] args)
{
List unsorted = new List();
List sorted;
Random random = new Random();
Console.WriteLine("Original array elements:" );
for(int i = 0; i< 10;i++){
unsorted.Add(random.Next(0,100));
Console.Write(unsorted[i]+" ");
}
Console.WriteLine();
sorted = MergeSort(unsorted);
Console.WriteLine("Sorted array elements: ");
foreach (int x in sorted)
{
Console.Write(x+" ");
}
Console.Write("\n");
}
private static List MergeSort(List unsorted)
{
if (unsorted.Count <= 1)
return unsorted;
List left = new List();
List right = new List();
int middle = unsorted.Count / 2;
for (int i = 0; i < middle;i++) //Dividing the unsorted list
{
left.Add(unsorted[i]);
}
for (int i = middle; i < unsorted.Count; i++)
{
right.Add(unsorted[i]);
}
left = MergeSort(left);
right = MergeSort(right);
return Merge(left, right);
}
private static List Merge(List left, List right)
{
List result = new List();
while(left.Count > 0 || right.Count>0)
{
if (left.Count > 0 && right.Count > 0)
{
if (left.First() <= right.First()) //Comparing First two elements to see which is smaller
{
result.Add(left.First());
left.Remove(left.First()); //Rest of the list minus the first element
}
else
{
result.Add(right.First());
right.Remove(right.First());
}
}
else if(left.Count>0)
{
result.Add(left.First());
left.Remove(left.First());
}
else if (right.Count > 0)
{
result.Add(right.First());
right.Remove(right.First());
}
}
return result;
}
}
}
Example 2: merge sort algo
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 # Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L) # Sorting the first half
mergeSort(R) # Sorting the second half
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+= 1
else:
arr[k] = R[j]
j+= 1
k+= 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i+= 1
k+= 1
while j < len(R):
arr[k] = R[j]
j+= 1
k+= 1
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i], end =" ")
print()
# driver code to test the above code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end ="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end ="\n")
printList(arr)