简体   繁体   中英

C# array sort explanation

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 :-

  1. Send Index element as 9
  2. Compare index element(9) with 2nd element(1)
  3. Swap Index element(9) and 2nd element(1) as 2nd element is smaller
  4. New array is 1,9,6,3
  5. Compare index element(1) with 3rd element(6)
  6. Do nothing
  7. Compare index element(1) with 4th element(3)
  8. Do nothing
  9. Array is 1,9,6,3

Iteration 2 will be :-

  1. Set Index element as 9
  2. Compare index element(9) with 3rd element(6)
  3. Swap Index element(9) and 3rd element(6) as 3rd element is smaller
  4. New array is 1,6,9,3
  5. Compare index element(6) with 4th element(3)
  6. Swap Index element(9) and 4th element(6) as 4th element is smaller
  7. Array is 1,3,9,6

Iteration 3 will be :-

  1. Set Index element as 9
  2. Compare index element(9) with 4th element(6)
  3. Swap Index element(9) and 4th element(6) as 4th element is smaller
  4. New array is 1,3,6,9

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM