## Introduction:

Sorting an array is a fundamental operation in computer science and programming. It allows us to arrange a collection of elements in a specific order for efficient searching, analyzing, or displaying purposes. In this blog post, we will explore different methods to sort an array in ascending order using C#. We will provide a step-by-step explanation of each method, along with code examples and their corresponding outputs.

## Method 1: Using Array.Sort() Method

The `Array.Sort()`

method is a built-in feature in C# that simplifies the sorting process. It automatically sorts an array in ascending order by default. Here's an example code snippet that demonstrates this method:

```
int[] numbers = { 5, 2, 8, 1, 9 };
Array.Sort(numbers);
foreach (int number in numbers)
{
Console.Write(number + " ");
}
```

### Output:

```
1 2 5 8 9
```

In this method, we start by initializing an integer array, `numbers`

, with unsorted elements. Then, we call the `Array.Sort()`

method, passing the `numbers`

array as an argument. This method sorts the elements of the array in ascending order. Finally, we iterate over the sorted array using a foreach loop and print each element.

## Method 2: Using the Bubble Sort Algorithm

The bubble sort algorithm is a simple and intuitive sorting technique. It repeatedly compares adjacent elements and swaps them if they are in the wrong order. Here's an example implementation in C#:

```
void BubbleSort(int[] array)
{
int n = array.Length;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (array[j] > array[j + 1])
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
// Usage example:
int[] numbers = { 5, 2, 8, 1, 9 };
BubbleSort(numbers);
foreach (int number in numbers)
{
Console.Write(number + " ");
}
```

### Output:

```
1 2 5 8 9
```

In this method, we define a `BubbleSort`

function that takes an integer array, `array`

, as a parameter. It utilizes nested loops to iterate over the array and compare adjacent elements. If the current element is greater than the next element, they are swapped. This process is repeated until the entire array is sorted. Finally, we invoke the `BubbleSort`

function with the `numbers`

array and print the sorted array.

## Method 3: Using the QuickSort Algorithm

QuickSort is a popular sorting algorithm known for its efficiency. It follows the divide-and-conquer approach and recursively partitions the array into smaller subarrays. Here's an example implementation in C#:

```
void QuickSort(int[] array, int low, int high)
{
if (low < high)
{
int pivot = Partition(array, low, high);
QuickSort(array, low, pivot - 1);
QuickSort(array, pivot + 1, high);
}
}
int Partition(int[] array, int low, int high)
{
int pivot = array[high];
int i = low - 1;
for (int j = low; j < high; j++)
{
if (array[j] < pivot)
{
i++;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int temp2 = array[i + 1];
array[i + 1] = array[high];
array[high] = temp2;
return i + 1;
}
// Usage example:
int[] numbers = { 5, 2, 8, 1, 9 };
QuickSort(numbers, 0, numbers.Length - 1);
foreach(int number in numbers)
{
Console.Write(number + " ");
}
```

### Output:

`1 2 5 8 9`

In this method, we define two functions: ``QuickSort`

` and ``Partition`

`. The ``QuickSort`

` function takes an array, ``array`

`, along with the low and high indices of the subarray to be sorted. It first selects a pivot element (in this case, the last element), partitions the array around the pivot, and recursively applies the quicksort algorithm to the subarrays on both sides of the pivot. The ``Partition`

` function is responsible for rearranging the array elements around the pivot. Finally, we invoke the ``QuickSort`

` function with the `numbers` array and print the sorted array.

## Method 4: Using the Selection Sort Algorithm

The selection sort algorithm is another straightforward approach to sorting an array. It works by repeatedly finding the minimum element from the unsorted part of the array and placing it at the beginning. Here's an example implementation in C#:

```
void SelectionSort(int[] array)
{
int n = array.Length;
for (int i = 0; i < n - 1; i++)
{
int minIndex = i;
for (int j = i + 1; j < n; j++)
{
if (array[j] < array[minIndex])
{
minIndex = j;
}
}
int temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
// Usage example:
int[] numbers = { 5, 2, 8, 1, 9 };
SelectionSort(numbers);
foreach (int number in numbers)
{
Console.Write(number + " ");
}
```

### Output:

```
1 2 5 8 9
```

In this method, we define a `SelectionSort`

function that takes an integer array, `array`

, as a parameter. The algorithm iterates over the array and selects the minimum element in the unsorted part. It then swaps that element with the first element of the unsorted part, effectively moving it to its correct position. This process is repeated until the entire array is sorted. Finally, we invoke the `SelectionSort`

function with the `numbers`

array and print the sorted array.

## Method 5: Using the Merge Sort Algorithm

Merge sort is a divide-and-conquer algorithm that divides the array into smaller subarrays, recursively sorts them, and merges them back together. It is known for its stability and efficiency. Here's an example implementation in C#:

```
void MergeSort(int[] array, int left, int right)
{
if (left < right)
{
int mid = (left + right) / 2;
MergeSort(array, left, mid);
MergeSort(array, mid + 1, right);
Merge(array, left, mid, right);
}
}
void Merge(int[] array, int left, int mid, int right)
{
int[] temp = new int[right - left + 1];
int i = left;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= right)
{
if (array[i] <= array[j])
{
temp[k++] = array[i++];
}
else
{
temp[k++] = array[j++];
}
}
while (i <= mid)
{
temp[k++] = array[i++];
}
while (j <= right)
{
temp[k++] = array[j++];
}
for (int m = 0; m < temp.Length; m++)
{
array[left + m] = temp[m];
}
}
// Usage example:
int[] numbers = { 5, 2, 8, 1, 9 };
MergeSort(numbers, 0, numbers.Length - 1);
foreach (int number in numbers)
{
Console.Write(number + " ");
}
```

### Output:

```
1 2 5 8 9
```

In this method, we define two functions: `MergeSort`

and `Merge`

. The `MergeSort`

function takes an array, `array`

, along with the left and right indices of the subarray to be sorted. It divides the array into smaller subarrays until they become individual elements. Then, it merges these subarrays in a sorted manner using the `Merge`

function. The `Merge`

function compares elements from both subarrays and places them back into the original array in the correct order. Finally, we invoke the `MergeSort`

function with the `numbers`

array and print the sorted array.

## Method 6: Using the Insertion Sort Algorithm

The insertion sort algorithm builds the final sorted array one element at a time. It iterates through the array, considering each element in turn and inserting it into its correct position within the already sorted part of the array. Here's an example implementation in C#:

```
void InsertionSort(int[] array)
{
int n = array.Length;
for (int i = 1; i < n; i++)
{
int key = array[i];
int j = i - 1;
while (j >= 0 && array[j] > key)
{
array[j + 1] = array[j];
j--;
}
array[j + 1] = key;
}
}
// Usage example:
int[] numbers = { 5, 2, 8, 1, 9 };
InsertionSort(numbers);
foreach (int number in numbers)
{
Console.Write(number + " ");
}
```

### Output:

```
1 2 5 8 9
```

In this method, we define an `InsertionSort`

function that takes an integer array, `array`

, as a parameter. The algorithm starts with the second element (index 1) and compares it to the elements in the sorted part of the array (elements before the current element). If the current element is smaller, it shifts the elements in the sorted part to the right to make space for the current element. This process is repeated until the entire array is sorted. Finally, we invoke the `InsertionSort`

function with the `numbers`

array and print the sorted array.

## Method 7: Using LINQ's OrderBy Method

C# provides LINQ (Language-Integrated Query) as a powerful tool for querying and manipulating data. The `OrderBy`

method in LINQ can be utilized to sort an array in ascending order. Here's an example implementation in C#:

```
int[] numbers = { 5, 2, 8, 1, 9 };
var sortedNumbers = numbers.OrderBy(num => num).ToArray();
foreach (int number in sortedNumbers)
{
Console.Write(number + " ");
}
```

### Output:

```
1 2 5 8 9
```

In this method, we start by initializing an integer array, `numbers`

, with unsorted elements. We then use the `OrderBy`

method from LINQ to sort the `numbers`

array in ascending order. The lambda expression `num => num`

specifies the sorting criterion, which is simply the elements themselves. Finally, we convert the sorted sequence back to an array using the `ToArray`

method and iterate over it to print the sorted elements.

## Conclusion:

In this blog post, we explored several methods to sort an array in ascending order using C#. We covered built-in methods like `Array.Sort()`

, sorting algorithms like bubble sort, quicksort, selection sort, and merge sort, as well as utilizing LINQ's `OrderBy`

method. Each method provided the desired output of sorting the given array. By understanding and applying these different techniques, you have a versatile set of tools to efficiently sort arrays based on your specific needs. Sorting is a fundamental operation in programming, and mastering these methods empowers you to organize data effectively and optimize the performance of your C# applications.

## Comments (0)