Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- //Write a method that return the maximal element in a portion of array of integers starting at given index.
- //Using it write another method that sorts an array in ascending / descending order.
- class SortArray
- {
- static void Main()
- {
- int[] myArray = { 7, 4, 5, 12, 1, 40, 25, 2 };
- Stack<int> stack = new Stack<int>();
- Sort(myArray,stack);
- Console.WriteLine("Descending sort:");
- foreach (var item in myArray)
- {
- Console.Write(item + " ");
- }
- Console.WriteLine();
- Console.WriteLine("Ascending sort:");
- foreach (var item in stack)
- {
- Console.Write(item + " ");
- }
- Console.WriteLine();
- }
- private static void Sort(int[] myArray,Stack<int> stack)
- {
- int max = 0;
- int maxIndex;
- for (int i = 0; i < myArray.Length; i++)
- {
- max = FindMax(myArray, i);
- maxIndex = Array.IndexOf(myArray,max);
- Swap(ref myArray[i], ref myArray[maxIndex]);
- stack.Push(myArray[i]);
- }
- }
- private static void Swap(ref int x, ref int y)
- {
- x ^= y;
- y ^= x;
- x ^= y;
- }
- private static int FindMax(int[] myArray, int pos)
- {
- int max = 0;
- for (int i = pos; i < myArray.Length; i++)
- {
- if (myArray[i] > max)
- {
- max = myArray[i];
- }
- }
- return max;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement