Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Mergesort
{
Class Program
{
Static Void Main ( String [] ARGs)
{
Int [] Arr = New Int [] { 1 , 8 , 3 , 5 };
Mergesort ( Ref Arr, 0 , Arr. Length - 1 );
Foreach ( Int Item In ARR)
{
Console. writeline (item );
}
Console. readkey ();
}
/// <Summary>
/// Merge Sorting
/// </Summary>
/// <Param name = "arr"> Array to be sorted, closed range </Param>
/// <Param name = "startindex"> Start position of sorting </Param>
/// <Param name = "endindex"> End position </Param>
Static Void Mergesort ( Ref Int [] Arr, Int Startindex, Int Endindex)
{
Int Mid;
// At least two data records exist.
If (Startindex < Endindex)
{
Mid = (Startindex + Endindex) / 2 ;
// Merge the First Half of sorting
Mergesort ( Ref Arr, startindex, mid );
// Second half
Mergesort ( Ref Arr, mid + 1 , Endindex );
// Merge
Merge ( Ref Arr,
Startindex,
Mid,
Endindex );
}
}
/// <Summary>
/// Merge two sorted arrays with closed intervals
/// [Startindex, midindex], [midindex + 1, endindex]
/// </Summary>
/// <Param name = "arr"> Sorted Array </Param>
/// <Param name = "startindex"> </param>
/// <Param name = "midindex"> </param>
/// <Param name = "endindex"> </param>
Static Void Merge ( Ref Int [] Arr,
Int Startindex,
Int Midindex,
Int Endindex)
{
Int N = Midindex - Startindex + 1 ;
Int M = Endindex - Midindex;
// Change Time with Space
Int [] Startarrcopy = New Int [N + 1 ];
Int [] Endarrcopy = New Int [M + 1 ];
// Copy an array
For ( Int I = 0 ; I < N; ++ I)
{
Startarrcopy [I] = Arr [I + Startindex];
}
For ( Int I = 0 ; I < M; ++ I)
{
Endarrcopy [I] = Arr [I + Midindex + 1 ];
}
// Set sentinel data
Startarrcopy [N] = Int . Maxvalue;
Endarrcopy [m] = Int . Maxvalue;
// Merge data into the original array
Int K = Startindex; // Total Length
Int A = 0 , B = 0 ; // Declare two cursors
While (K <= Endindex)
{
If (Startarrcopy [A] > Endarrcopy [B])
{
// Sort in ascending order
Arr [k] = Endarrcopy [B];
++ B;
}
Else
{
Arr [k] = Startarrcopy [a];
++ A;
}
++ K;
}
}
}
}
// Configure //-----------------------------------------------------------------------------------------------
Updated:
Rewrite the preceding Merge Sorting to a generic method and add it to easycoding'sProgramLibrary, and add unit test program, test passed, add sortingAlgorithm. Below isCode:/Files/xuqiang/mergesorter.rar