Advertisement
sashomaga

Sort

Jan 16th, 2013
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.58 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. //Write a method that return the maximal element in a portion of array of integers starting at given index.
  4. //Using it write another method that sorts an array in ascending / descending order.
  5. class SortArray
  6. {
  7.     static void Main()
  8.     {
  9.         int[] myArray = { 7, 4, 5, 12, 1, 40, 25, 2 };
  10.         Stack<int> stack = new Stack<int>();
  11.         Sort(myArray,stack);
  12.         Console.WriteLine("Descending sort:");
  13.         foreach (var item in myArray)
  14.         {
  15.             Console.Write(item + " ");
  16.         }
  17.         Console.WriteLine();
  18.         Console.WriteLine("Ascending sort:");      
  19.         foreach (var item in stack)
  20.         {
  21.             Console.Write(item + " ");
  22.         }
  23.         Console.WriteLine();
  24.     }
  25.  
  26.     private static void Sort(int[] myArray,Stack<int> stack)
  27.     {
  28.         int max = 0;
  29.         int maxIndex;
  30.         for (int i = 0; i < myArray.Length; i++)
  31.         {
  32.             max = FindMax(myArray, i);
  33.             maxIndex = Array.IndexOf(myArray,max);
  34.             Swap(ref myArray[i], ref myArray[maxIndex]);
  35.             stack.Push(myArray[i]);            
  36.         }                
  37.     }
  38.  
  39.     private static void Swap(ref int x, ref int y)
  40.     {
  41.         x ^= y;
  42.         y ^= x;
  43.         x ^= y;
  44.     }
  45.  
  46.     private static int FindMax(int[] myArray, int pos)
  47.     {
  48.         int max = 0;
  49.         for (int i = pos; i < myArray.Length; i++)
  50.         {
  51.             if (myArray[i] > max)
  52.             {
  53.                 max = myArray[i];
  54.             }
  55.         }
  56.         return max;
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement