Part 5. Write a Program Array in Ascending Order.
We will learn to sort an array in C# using inbuilt and without using an inbuilt C# function.
- Sort an Array in Ascending Order.
- Sort an array in ascending order without using inbuilt C# function.
1.Sort an Array in Ascending Order.
Array.Sort() is inbuilt function to sort an array.
class Program
{
static void Main(string[] args)
{
//initializing the array
int[] arr = { 1, 4, 2, 5, 6 };
//Sort the array inbuilt function by .Net
Array.Sort(arr);
foreach (var item in arr)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
Output :
1
2
4
5
6
- Sort an array in ascending order without using inbuilt C# function
We will take two for loops; first, a for loop for checking the first position of an array and iterating the length of the array. The second loop starts with the i+1 position and iterates the length of the array.
class Program
{
static void Main(string[] args)
{
int temp=0;
//initializing the array
int[] arr = { 1, 4, 2, 5, 6 };
for (int i = 0; i <= arr.Length-1; i++)
{
for (int j = i+1; j < arr.Length; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
foreach (var item in arr)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
Output
1
2
4
5
6