Advertisement
Klaxon

[C# Arrays] Increasing Order Sort

Sep 30th, 2013
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.79 KB | None | 0 0
  1. // 18. * Write a program that reads an array of integers and removes from it a minimal number of elements in such way that the remaining array is sorted in increasing order. Print the remaining sorted array.
  2. // Example: {6, 1, 4, 3, 0, 3, 6, 4, 5} -> {1, 3, 3, 4, 5}
  3.  
  4. using System;
  5. using System.Collections.Generic;
  6.  
  7. class IncreasingOrderSort // With a lot of help :(
  8. {
  9.     static bool isSorted(List<int> list)
  10.     {
  11.         bool isSorted = true;
  12.  
  13.         for (int i = 0; i < list.Count - 1; i++)
  14.         {
  15.             if (list[i] > list[i + 1])
  16.             {
  17.                 isSorted = false;
  18.             }
  19.         }
  20.  
  21.         return isSorted;
  22.     }
  23.  
  24.     // Printing
  25.     static void PrintList(List<int> list)
  26.     {
  27.         for (int i = 0; i < list.Count; i++)
  28.         {
  29.             Console.Write(list[i] + " ");
  30.         }
  31.         Console.WriteLine();
  32.     }
  33.  
  34.     // Main magic
  35.     static void Main()
  36.     {
  37.         List<int> arrayOfNumbers = new List<int>() { 6, 1, 4, 3, 0, 3, 6, 4, 5 };
  38.         List<int> result = new List<int>();
  39.  
  40.         int maxi = (int)Math.Pow(2, arrayOfNumbers.Count) - 1;
  41.         int maxElements = 0;
  42.  
  43.         for (int i = 1; i <= maxi; i++)
  44.         {
  45.             List<int> temporaryList = new List<int>();
  46.             int counter = 0;
  47.  
  48.             for (int j = 1; j <= arrayOfNumbers.Count; j++)
  49.             {
  50.                 if (((i >> (j - 1)) & 1) == 1)
  51.                 {
  52.                     temporaryList.Add(arrayOfNumbers[j - 1]);
  53.                     counter++;
  54.                 }
  55.             }
  56.  
  57.             if (counter > maxElements && isSorted(temporaryList))
  58.             {
  59.                 result = temporaryList;
  60.                 maxElements = counter;
  61.             }
  62.  
  63.             counter = 0;
  64.         }
  65.  
  66.         PrintList(result);
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement