sort array without sort function in csharp

To sort an array without using the built-in sort() function in C#, you can use any of the sorting algorithms like bubble sort, selection sort, insertion sort, and so on. Here's an example of a bubble sort algorithm to sort an array in ascending order:

main.cs
int[] arr = { 64, 34, 25, 12, 22, 11, 90 };
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;
        }
    }
}
341 chars
17 lines

In the above code, we use nested for loops to traverse the array and compare adjacent elements. If the elements are not in the correct order, we swap them. We continue this process until the entire array is sorted in ascending order.

related categories

gistlibby LogSnag