In this blog, we will learn to sort an array in C# without using an inbuilt C# function. We will learn ascending order and descending order array with a simple example.
Sort Array In C# Without Using Inbuilt Function
Example 1 - Sort an array in ascending order without using inbuilt C# function
We will create a simple one integer array having values 2,9,4,3,5,1,7 in the array as described in the following example. 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.
  1. using System;
  2. namespace SortArrayExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. int[] intArray = new int[] {2,9,4,3,5,1,7 };
  9. int temp = 0;
  10. for (int i = 0; i <= intArray.Length-1; i++)
  11. {
  12. for (int j = i+1; j < intArray.Length; j++)
  13. {
  14. if (intArray[i] > intArray[j])
  15. {
  16. temp = intArray[i];
  17. intArray[i] = intArray[j];
  18. intArray[j] = temp;
  19. }
  20. }
  21. }
  22. Console.WriteLine("Array sort in asscending order");
  23. foreach (var item in intArray)
  24. {
  25. Console.WriteLine(item);
  26. }
  27. Console.ReadLine();
  28. }
  29. }
  30. }
Output
Sort Array In C# Without Using Inbuilt Function
Example 2
Sort an array in descending order without using inbuilt C# function.
  1. using System;
  2. namespace SortArrayExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. int[] intArray = new int[] {2,9,4,3,5,1,7 };
  9. int temp = 0;
  10. for (int i = 0; i <= intArray.Length-1; i++)
  11. {
  12. for (int j = i+1; j < intArray.Length; j++)
  13. {
  14. if (intArray[i] < intArray[j])
  15. {
  16. temp = intArray[i];
  17. intArray[i] = intArray[j];
  18. intArray[j] = temp;
  19. }
  20. }
  21. }
  22. Console.WriteLine("Array sort in descending order");
  23. foreach (var item in intArray)
  24. {
  25. Console.WriteLine(item);
  26. }
  27. Console.ReadLine();
  28. }
  29. }
  30. }
Output
Sort Array In C# Without Using Inbuilt Function
I hope you understand how to sort an array without using the inbuilt function.