Can someone please explain how the for loops works here after iterating through all indexes. I'm not understanding how the for loops are working again and again until all the numbers are sorted.
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] {9,1,6,3,7,2,4};
int temp = 0;
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length;j++)
{
if(arr[i]>arr[j])
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
Console.Write(arr[i]+",");
}
Console.ReadLine();
}
This is a bubble sort. Herein you sort the array in ascending order. You do this by comparing the index element with all the other elements in the array and ensuring that the index element in the smallest one.
Suppose the array has only 4 elements :-
9,1,6,3
Iteration 1 will be :-
Iteration 2 will be :-
Iteration 3 will be :-
Now the array is sorted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.