Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Program
- {
- static void Main(string[] args)
- {
- //variable used to count how many times the array is shuffled.
- int count = 0;
- Random r = new Random();
- int rand;
- //initializing our array and assigning it random values between 1 and 50.
- int[] arr = new int[5];
- for (int i = 0; i < arr.Length; i++)
- {
- arr[i] = rand = r.Next(1, 51);
- }
- //uses method to print our filled array
- PrintArray(arr);
- //shuffle and prints our array until the values are in order according to the return bool from CheckArray
- do
- {
- ShuffleArray(arr);
- PrintArray(arr);
- count++;
- } while (CheckArray(arr) == false);
- Console.WriteLine("Array has been sorted in ascending order.");
- Console.WriteLine("Attempts Taken: " + count);
- Console.Read();
- }
- static bool CheckArray(int[] arr)
- {
- if (arr[0] <= arr[1] && arr[1] <= arr[2] && arr[2] <= arr[3] && arr[3] <= arr[4])
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- static int[] ShuffleArray(int[] arr)
- {
- Random r = new Random();
- for (int i = 0; i < arr.Length; i++)
- {
- swap(arr, i, i + r.Next(arr.Length - i));
- }
- return arr;
- }
- //pulls in our array, our current index position, and a random index of the remaining selection of indices.
- static void swap(int[] arr, int i, int b)
- {
- int temp = arr[i];
- arr[i] = arr[b];
- arr[b] = temp;
- }
- //Prints our current array to the console.
- static void PrintArray(int[] arr)
- {
- for (int i = 0; i < arr.Length; i++)
- {
- Console.Write("|" + arr[i] + "|");
- }
- Console.WriteLine("\n");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement