ellapt

T9.9.SelectSortAscDesc

Jan 19th, 2013
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.87 KB | None | 0 0
  1. using System;
  2.  
  3. class SelectSortAscDesc
  4. {
  5. static void maxElem(int index, int[] array)
  6. {
  7. int i = index;
  8. for (int j = i + 1; j < array.Length; j++)
  9. {
  10. if (array [j] < array [index])
  11. {
  12. index = j;
  13. }
  14. }
  15. if (index != i)
  16. {
  17. swapElem(i, index, array);
  18. }
  19. }
  20.  
  21. static void minElem(int index, int[] array)
  22. {
  23. int i = index;
  24. for (int j = i + 1; j < array.Length; j++)
  25. {
  26. if (array[j] > array[index])
  27. {
  28. index = j;
  29. }
  30. }
  31. if (index != i)
  32. {
  33. swapElem(i, index, array);
  34. }
  35. }
  36.  
  37. static void swapElem(int ind1, int ind2, int[] arr)
  38. {
  39. int temp = arr[ind1];
  40. arr[ind1] = arr[ind2];
  41. arr [ind2] = temp;
  42. }
  43.  
  44. static void Main()
  45. {
  46. string inputVar;
  47. uint n;
  48. Console.WriteLine("Write a method to return the max element \nin a portion of int array starting at given index.");
  49. Console.WriteLine(" Using it write another method that sorts an array \nin ascending / descending order.");
  50. do
  51. {
  52. Console.Write("Enter array length: ");
  53. }
  54. while (!(uint.TryParse(inputVar = Console.ReadLine(), out n)) || n == 0);
  55.  
  56. do
  57. {
  58. Console.Write("Enter sort: a-ascending; d-descending: ");
  59. inputVar=Console.ReadLine();
  60. }
  61. while (!(inputVar=="a" || inputVar == "d"));
  62.  
  63. int[] arrayOfints = new int[n];
  64.  
  65. Console.WriteLine("Now enter the elements of the array:");
  66. for (int i = 0; i < n; i++)
  67. {
  68. arrayOfints[i] = int.Parse(Console.ReadLine());
  69. }
  70.  
  71. int minIndex = 0;
  72. for (int i = 0; i < n - 1; i++)
  73. {
  74. minIndex = i;
  75. if (inputVar == "a")
  76. {
  77. maxElem(minIndex, arrayOfints);
  78. }
  79. else if (inputVar == "d")
  80. {
  81. minElem(minIndex, arrayOfints);
  82. }
  83. }
  84. switch (inputVar)
  85. {
  86. case "a":
  87. Console.WriteLine("The array after selection sort ascending:");
  88. for (int k = 0; k < n; k++)
  89. {
  90. Console.Write("{0} ", arrayOfints[k]);
  91. }
  92. break;
  93. case "d":
  94. Console.WriteLine("The array after selection sort descending:");
  95. for (int k = 0; k < n; k++)
  96. {
  97. Console.Write("{0} ", arrayOfints[k]);
  98. }
  99. break;
  100. }
  101. Console.WriteLine();
  102. }
  103. }
Advertisement
Add Comment
Please, Sign In to add comment