ellapt

T7.7.SelectionSort

Jan 15th, 2013
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. using System;
  2.  
  3. class SelectionSort
  4. {
  5. static void Main()
  6. {
  7. string inputVar;
  8. uint n;
  9. Console.WriteLine("Sort an array using \"selection sort\" method");
  10. do
  11. {
  12. Console.Write("Enter array length: ");
  13. }
  14. while (!(uint.TryParse(inputVar = Console.ReadLine(), out n)) || n == 0);
  15.  
  16. int[] arrayOfints = new int[n];
  17.  
  18. Console.WriteLine("Now enter the elements of the array:");
  19. for (int i = 0; i < n; i++)
  20. {
  21. arrayOfints[i] = int.Parse(Console.ReadLine());
  22. }
  23.  
  24. int minIndex = 0;
  25. int temp;
  26. for (int i = 0; i < n - 1; i++)
  27. {
  28. minIndex = i;
  29. for (int j = i + 1; j < n; j++)
  30. {
  31. if (arrayOfints[j] < arrayOfints[minIndex])
  32. {
  33. minIndex = j;
  34. }
  35. }
  36. if (minIndex != i)
  37. {
  38. temp = arrayOfints[i];
  39. arrayOfints[i] = arrayOfints[minIndex];
  40. arrayOfints[minIndex] = temp;
  41. }
  42. }
  43. Console.WriteLine("The array after selection sort ascending:");
  44. for (int i = 0; i < n; i++)
  45. {
  46. Console.Write("{0} ", arrayOfints[i]);
  47. }
  48. Console.WriteLine();
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment