Hi Ahmed,
What do you mean by "i cannot do that"? This is because the code is fine, only that you are missing the comments indicator (//).
for (int j = 0; j <= a.Length - 2; j++)
{
for (int i = 0; i <= a.Length - 2; i++)
...........................
...........................
The algorithm checks for every two consecutive numbers and swaps them if necessary (for sorting). After one complete sweep (and swapping of numbers as needed), it starts sweeping again the whole list (starting from the beginning) and swaps numbers as necessary. The first loop (outer) makes sure it traverses the entire array n times (n = number of elements in the array). The second loop (inner) makes sure it swaps numbers in each traversal.
There are several variants of bubble sort. Complexity of this one is O(n-squared) as it traverses 'n x n' times in total. So in terms of algorithmic complexity this one is not a very good one.
The best way to understand the sorting is running the application in Visual Studio IDE in debug mode.
1) Place a breakpoint on the for loop and start the application (F5).
2) Then open the
autos
window (click on
menu->Debug->Windows->Autos
)
3) Also open the
locals
window (click on
menu->Debug->Windows->Autos
)
4) These two windows will enable you to view the values as you debug line-by-line.
5) Now press F10 and the code will be executed line-by-line. You can see changes in variables in RED in the
autos
and
locals
windows. The array 'a' should be inside
locals
window.
Please Google more for a lot of articles on different variants of bubble sort.