'How to print this sequence

Bubble Sort algorithm using C# and print this formate

Sample Input :

5
5 4 3 2 1

Sample Output:

4 3 2 1 5
3 2 1 4 5
2 1 3 4 5
1 2 3 4 5
1 2 3 4 5


int n = Convert.ToInt32(Console.ReadLine());
            int i, j,temp;
            int[] array = new int[n];
            string a = Console.ReadLine();
            var aa = a.Split(' ');

            for( i=0; i<n; i++)
            {
                array[i] = Convert.ToInt32(aa[i]);
            }

            for(i=n-1; i>=0; i--)
            {
                for(j=n-2; j>=1; j--)
                {
                    if (array[i] < array[j])
                    {
                        temp = array[j];
                        array[j] = array[i];
                        array[i] = temp;
                    }
                    
                    
                }
                
            }


Solution 1:[1]

According to the ouput required you should implement selection sort, not bubble one.

// Actually, we don't need this value
int n = int.Parse(Console.ReadLine());

int[] array = Console
  .ReadLine()
  .Split(' ')
  .Select(line => int.Parse(line))
  .ToArray();

for (int index = array.Length - 1; index >= 1; --index) {
  Console.WriteLine(string.Join(" ", array));

  int maxIndex = 0;
  int max = array[0];

  for (int i = 0; i <= index; ++i) 
    if (array[i] > max) {
      max = array[i];
      maxIndex = i;
    }
   
  for (int i = maxIndex; i < index; ++i) 
    (array[i], array[i + 1]) = (array[i + 1], array[i]);
        
  array[index] = max;
}

Console.Write(string.Join(" ", array));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitry Bychenko