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];
& Nb