C# Program to sort an array in ascending order


In this program, You will learn how to sort an array in ascending order in C#.


List is: 5 4 2 3 1

After sort list is: 1 2 3 4 5

Example: How to sort an array in ascending order in C#.

using System;
public class Program
{
	public static void Main(string[] args)
	{
		int temp;
		int[] arr = new int[5];

		Console.Write("Enter five numbers:");
		for (int i = 0; i < arr.Length; i++)
		{
			arr[i] = Convert.ToInt32(Console.ReadLine());
		}

		for (int i = 0; i < arr.Length; i++)
		{
			for (int j = 1 + i; j < arr.Length; j++)
			{
				if (arr[i] > arr[j])
				{
					temp = arr[i];
					arr[i] = arr[j];
					arr[j] = temp;
				}
			}
		}

		Console.Write("Array list after sorting:");
		for (int i = 0; i < arr.Length; i++)
		{
			Console.Write(arr[i] + " ");
		}
	}
}

Output:

Enter five numbers:20
30
10
50
40
Array list after sorting:10 20 30 40 50