Preface
A feature developed in the afternoon involves sorting. Here we will list it and make a simple performance comparison. This article is used as a record, so it will not be nonsense. You can directly go to the code.
Public class Sort
{
Public void Test ()
{
Int Num = 10000;
Int [] iArrary = GetList (Num );
Stopwatch watch = new Stopwatch ();
Watch. Start ();
BubbleSorter (iArrary );
Watch. Stop ();
Console. WriteLine (watch. ElapsedMilliseconds. ToString ());
// Desplay (iArrary );
IArrary = GetList (Num );
Watch. Reset ();
Watch. Start ();
SelectionSorter (iArrary );
Watch. Stop ();
Console. WriteLine (watch. ElapsedMilliseconds. ToString ());
// Desplay (iArrary );
IArrary = GetList (Num );
Watch. Reset ();
Watch. Start ();
InsertionSorter (iArrary );
Watch. Stop ();
Console. WriteLine (watch. ElapsedMilliseconds. ToString ());
// Desplay (iArrary );
IArrary = GetList (Num );
Watch. Reset ();
Watch. Start ();
ShellSorter (iArrary );
Watch. Stop ();
Console. WriteLine (watch. ElapsedMilliseconds. ToString ());
// Desplay (iArrary );
}
Private int [] GetList (int Num)
{
Int [] array = new int [Num];
Random rd = new Random ();
For (int I = 0; I <Num; I ++)
{
Array [I] = rd. Next (0, Num );
}
Return array;
}
Private void Desplay (int [] list)
{
Foreach (int item in list)
{
Console. WriteLine (item. ToString ());
}
}
/// <Summary>
/// Bubble sort
/// </Summary>
/// <Param name = "list"> </param>
Public void BubbleSorter (int [] list)
{
Int I, j, temp;
Bool done = false;
J = 1;
While (j <list. Length )&&(! Done ))
{
Done = true;
For (I = 0; I <list. Length-j; I ++)
{
If (list [I]> list [I + 1])
{
Done = false;
Temp = list [I];
List [I] = list [I + 1];
List [I + 1] = temp;
}
}
J ++;
}
}
/// <Summary>
/// Select sorting
/// </Summary>
/// <Param name = "list"> </param>
Public void SelectionSorter (int [] list)
{
Int min;
For (int I = 0; I <list. Length-1; I ++)
{
Min = I;
For (int j = I + 1; j <list. Length; j ++)
{
If (list [j] <list [min])
Min = j;
}
Int t = list [min];
List [min] = list [I];
List [I] = t;
}
}
/// <Summary>
/// Insert sorting
/// </Summary>
/// <Param name = "list"> </param>
Public void InsertionSorter (int [] list)
{
For (int I = 1; I <list. Length; I ++)
{
Int t = list [I];
Int j = I;
While (j> 0) & (list [J-1]> t ))
{
List [j] = list [J-1];
-- J;
}
List [j] = t;
}
}
/// <Summary>
/// Sort by hill
/// </Summary>
/// <Param name = "list"> </param>
Public void ShellSorter (int [] list)
{
Int inc;
For (inc = 1; inc <= list. Length/9; inc = 3 * inc + 1 );
For (; inc> 0; inc/= 3)
{
For (int I = inc + 1; I <= list. Length; I + = inc)
{
Int t = list [I-1];
Int j = I;
While (j> inc) & (list [j-inc-1]> t ))
{
List [J-1] = list [j-inc-1];
J-= inc;
}
List [J-1] = t;
}
}
}
}
Num = 100 then all four algorithms are 0 MS.
Num = 1000 bubble 6, select 3, insert 2, Hill 2
Num = 10000 bubble 612, select 309, insert 189, Hill 182
Make a simple record