Write C# program to sort an array in ascending order


Introduction

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. using System;
  2. class Program
  3. {
  4. static void Main()
  5. {
  6. int[] arr = new int[100];;
  7. int size, i, j, temp;
  8.  
  9. //Reads size of the array
  10. Console.WriteLine("Enter size of the array: ");
  11. size = Convert.ToInt32(Console.ReadLine());
  12. //Reads elements in array
  13. Console.WriteLine("Enter elements in the array: ");
  14. for(i=0; i<size; i++)
  15. {
  16. arr[i] = Convert.ToInt32(Console.ReadLine());
  17. }
  18.  
  19. //Sorting an array in ascending order
  20.  
  21. for (i = 0; i < size; i++)
  22. {
  23. for (j = i + 1; j < size; j++)
  24. {
  25. //If there is a smaller element found on right of the array then swap it.
  26. if (arr[j] < arr[i])
  27. {
  28. temp = arr[i];
  29. arr[i] = arr[j];
  30. arr[j] = temp;
  31. }
  32. }
  33. }
  34. //Printing the sorted array in ascending order
  35.  
  36. Console.WriteLine("Elements of array in sorted ascending order:");
  37. for (i = 0; i < size; i++)
  38. {
  39. Console.WriteLine(arr[i]);
  40. }
  41. Console.ReadLine();
  42. }
  43.  
  44. }

Result

C# language techstudy.org

     





Related Topics




Popular Posts