Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. //variable used to count how many times the array is shuffled.
  6. int count = 0;
  7.  
  8. Random r = new Random();
  9. int rand;
  10.  
  11. //initializing our array and assigning it random values between 1 and 50.
  12. int[] arr = new int[5];
  13. for (int i = 0; i < arr.Length; i++)
  14. {
  15. arr[i] = rand = r.Next(1, 51);
  16. }
  17.  
  18. //uses method to print our filled array
  19. PrintArray(arr);
  20.  
  21. //shuffle and prints our array until the values are in order according to the return bool from CheckArray
  22. do
  23. {
  24. ShuffleArray(arr);
  25. PrintArray(arr);
  26. count++;
  27. } while (CheckArray(arr) == false);
  28. Console.WriteLine("Array has been sorted in ascending order.");
  29. Console.WriteLine("Attempts Taken: " + count);
  30. Console.Read();
  31. }
  32.  
  33. static bool CheckArray(int[] arr)
  34. {
  35. if (arr[0] <= arr[1] && arr[1] <= arr[2] && arr[2] <= arr[3] && arr[3] <= arr[4])
  36. {
  37. return true;
  38. }
  39. else
  40. {
  41. return false;
  42. }
  43. }
  44. static int[] ShuffleArray(int[] arr)
  45. {
  46. Random r = new Random();
  47. for (int i = 0; i < arr.Length; i++)
  48. {
  49. swap(arr, i, i + r.Next(arr.Length - i));
  50. }
  51. return arr;
  52. }
  53.  
  54. //pulls in our array, our current index position, and a random index of the remaining selection of indices.
  55. static void swap(int[] arr, int i, int b)
  56. {
  57. int temp = arr[i];
  58. arr[i] = arr[b];
  59. arr[b] = temp;
  60. }
  61.  
  62. //Prints our current array to the console.
  63. static void PrintArray(int[] arr)
  64. {
  65. for (int i = 0; i < arr.Length; i++)
  66. {
  67. Console.Write("|" + arr[i] + "|");
  68. }
  69. Console.WriteLine("\n");
  70. }
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement