C# program to sort an array in ascending order
There are two ways to sort an array in ascending order:
1- By using the built-in Array.Sort method:
using System;
public class Program {
public static void Main(string[] args) {
int[] numbers = { 5, 2, 8, 3, 1, 9, 4, 6, 7 };
// Sort the array in ascending order
Array.Sort(numbers);
Console.WriteLine("Sorted array in ascending order:");
foreach (int num in numbers) {
Console.Write(num + " ");
}
}
}
In this program, we have an array of integers called numbers with some unsorted values. We use the Array.Sort method to sort the array in ascending order. After sorting, we iterate over the sorted array and print each element to the console.
The program outputs the sorted array in ascending order:
Sorted array in ascending order:
1 2 3 4 5 6 7 8 9
Note that the Array.Sort method modifies the original array in-place, so there's no need to assign the sorted result to a new variable.
2- By any sorting algorithm:
If you want to sort an array in ascending order without using the built-in Array.Sort method, you can implement a sorting algorithm like Bubble Sort or Selection Sort. Here's an example of using the Bubble Sort algorithm in C# to sort an array in ascending order:
using System;
public class Program {
public static void Main(string[] args) {
int[] numbers = { 5, 2, 8, 3, 1, 9, 4, 6, 7 };
// Sort the array in ascending order using Bubble Sort
BubbleSort(numbers);
Console.WriteLine("Sorted array in ascending order:");
foreach (int num in numbers) {
Console.Write(num + " ");
}
}
public static void BubbleSort(int[] arr) {
int n = arr.Length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
In this program, we have an array of integers called numbers with unsorted values. We define the BubbleSort method that implements the Bubble Sort algorithm to sort the array in ascending order. The outer loop iterates n - 1 times, where n is the length of the array. The inner loop compares adjacent elements and swaps them if they are in the wrong order. After each iteration of the outer loop, the largest element "bubbles" up to its correct position. Finally, we iterate over the sorted array and print each element to the console.
The program outputs the sorted array in ascending order:
Sorted array in ascending order:
1 2 3 4 5 6 7 8 9
Note that Bubble Sort is not the most efficient sorting algorithm, especially for large arrays, as it has a worst-case and average time complexity of O(n^2). There are more efficient sorting algorithms like Quick Sort or Merge Sort that you can explore for better performance.