Today we will introduce the traversal sorting method in C #. Today we will introduce the bubble method, direct Insertion Method and selection sorting method.
1. Bubble Method
Question: Use the Bubble Method to sort elements in the array from small to large.
Method 1:
Int [] arr = new int [] {3, 9, 27, 6, 18, 12, 21, 15 };
Foreach (int m in arr)
{
Console. Write (m + "");
}
Console. WriteLine ();
Int j, temp;
For (int I = 0; I <arr. Length-1; I ++)
{
J = I + 1;
Id:
If (arr [I]> arr [j])
{
Temp = arr [I];
Arr [I] = arr [j];
Arr [j] = temp;
Goto id;
}
Else
{
If (j <arr. Length-1)
{
J ++;
Goto id;
}
}
}
Foreach (int n in arr)
{
Console. Write (n + "");
}
Console. WriteLine ();
Console. ReadLine ();
Method 2:
Int [] arr = new int [] {3, 9, 27, 6, 18, 12, 21, 15 };
Int I, j, temp;
Bool done = false;
J = 1;
While (j <arr. Length )&&(! Done ))
{
Done = true;
For (I = 0; I <arr. Length-j; I ++)
{
If (arr [I]> arr [I + 1])
{
Done = false;
Temp = arr [I];
Arr [I] = arr [I + 1];
Arr [I + 1] = temp;
}
}
J ++;
}
Foreach (int n in arr)
{
Console. Write (n + "--");
}
Console. WriteLine ();
Console. ReadLine ();
2. Insert sorting method
Int [] arr = new int [] {3, 9, 27, 6, 18, 12, 21, 15 };
Foreach (int n in arr)
Console. Write ("{0}", n + "");
Console. WriteLine ();
For (int I = 0; I <6; ++ I)
{
Int temp = arr [I];
Int j = I;
While (j> 0) & (arr [j-1]> temp ))
{
Arr [j] = arr [j-1];
-- J;
}
Arr [j] = temp;
}
Console. WriteLine ("sorting result :");
Foreach (int n in arr)
Console. Write ("{0}", n + "");
Console. WriteLine ();
3. Select sorting method
Int [] arr = new int [] {3, 9, 27, 6, 18, 12, 21, 15 };
Foreach (int n in arr)
Console. Write ("{0}", n + "");
Console. WriteLine ();
Int min;
For (int I = 0; I <arr. Length-1; I ++)
{
Min = I;
For (int j = I + 1; j <arr. Length; j ++)
{
If (arr [j] <arr [min])
Min = j;
}
Int t = arr [min];
Arr [min] = arr [I];
Arr [I] = t;
}
Console. WriteLine ("sorting result :");
Foreach (int n in arr)
Console. Write ("{0}", n + "");
Console. WriteLine ();
In addition, in C #, Sort the array. Microsoft provides the Sort and Reverse methods. The Sort method sorts the array elements in ascending order, and the Reverse method sorts the array elements in Reverse order.