Advertisement
Hristo_B

Arrays.SortArrayWithMinRemoving

Jul 2nd, 2013
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class SortArrayWithMinRemoving
  5. {
  6.     //* Write a program that reads an array of integers and removes from it a minimal number of elements
  7.     //in such way that the remaining array is sorted in increasing order.
  8.     //Print the remaining sorted array. Example:
  9.     //{6, 1, 4, 3, 0, 3, 6, 4, 5}  {1, 3, 3, 4, 5}
  10.     static bool CheckIfSorted(List<int> listOfInt)
  11.     {
  12.         int counter = 0;
  13.         for (int i = 0; i < listOfInt.Count-1; i++)
  14.         {
  15.             if (listOfInt[i] <= listOfInt[i + 1])
  16.             {
  17.                 counter++;
  18.             }
  19.         }
  20.         if (counter == listOfInt.Count-1)
  21.         {
  22.             return true;
  23.         }
  24.         else
  25.         {
  26.             return false;
  27.         }
  28.     }
  29.  
  30.     static void Main()
  31.     {
  32.         int[] arr = { 6, 1, 4, 3, 0, 3, 6, 4, 5, 8,7, 3, 9, 101 };
  33.  
  34.         Console.WriteLine("Array unsorted:\n{0}", string.Join(", ", arr));
  35.         List<int> maxList = new List<int>();
  36.         List<int> sortedArray = new List<int>();
  37.  
  38.         int combinations = (int)Math.Pow(2, arr.Length);
  39.  
  40.         for (int i = combinations - 1; i > 0; i--)
  41.         {
  42.             for (int j = 0; j < arr.Length; j++)
  43.             {
  44.                 int mask = 1 << j;
  45.                 int iAndMask = mask & i;
  46.                 int bit = iAndMask >> j;
  47.  
  48.                 if (bit == 1)
  49.                 {
  50.                     sortedArray.Add(arr[j]);
  51.                 }
  52.             }
  53.  
  54.             if (CheckIfSorted(sortedArray) == true)
  55.             {
  56.                 if (sortedArray.Count > maxList.Count)
  57.                 {
  58.                     maxList.Clear();
  59.                     for (int k = 0; k < sortedArray.Count; k++)
  60.                     {
  61.                         maxList.Add(sortedArray[k]);
  62.                     }
  63.                 }
  64.                 sortedArray.Clear();
  65.             }
  66.             else
  67.             {
  68.                 sortedArray.Clear();
  69.             }
  70.         }
  71.         Console.WriteLine("Array sorted:\n{0}", string.Join(", ", maxList));
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement