stkirov

18.IncreasingElements

Jan 6th, 2013
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.37 KB | None | 0 0
  1. //* 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. Example:
  2. //  {6, 1, 4, 3, 0, 3, 6, 4, 5}  {1, 3, 3, 4, 5}
  3. using System;
  4. using System.Collections.Generic;
  5.  
  6. class IncreasingElements
  7. {
  8.     static void Main()
  9.     {
  10.         int[] array = { 7,1,8,0,9,2 };
  11.  
  12.         List<int> sorted = new List<int>();
  13.         sorted.Add(int.MinValue);
  14.         for (int i = 0, j = i + 1; i < array.Length; i += 2, j += 2)
  15.         {
  16.             if (i==array.Length-1 && array[i]>=sorted[sorted.Count-1]) //to work for arrays with odd number of elements
  17.             {
  18.                 sorted.Add(array[i]);
  19.                 break;
  20.             }
  21.             else if (i==array.Length-1)
  22.             {
  23.                 break;
  24.             }
  25.             if (array[j]-array[i]==1 || array[i]<0) //to work for folowing numbers and negative numbers
  26.             {
  27.                 sorted.Add(array[i]);
  28.                 sorted.Add(array[j]);
  29.                 continue;
  30.             }
  31.                 if (Math.Min(array[i], array[j]) == array[i] && sorted[sorted.Count-1]<=array[i]) //if i is min and i is bigger than the last number in the list
  32.                 {
  33.                     sorted.Add(array[i]);
  34.                 }
  35.                 else if (array[i] < sorted[sorted.Count - 1] && array[j] >= sorted[sorted.Count - 1]) //if i is smaller than the last number in the list and j is greater than the last number in the list
  36.                 {
  37.                     sorted.Add(array[j]);
  38.                     continue;
  39.                 }
  40.                 if (Math.Min(array[i], array[j]) == array[j] && sorted[sorted.Count - 1] <= array[j])  //if j is min and j is bigger than the last number in the list
  41.                 {
  42.                     sorted.Add(array[j]);
  43.                 }
  44.                 else if (array[j] < sorted[sorted.Count - 1] && array[i] >= sorted[sorted.Count - 1])//if j is smaller than the last number in the list and i is greater than the last number in the list
  45.                 {
  46.                     sorted.Add(array[i]);
  47.                 }
  48.         }
  49.         foreach (var item in sorted)
  50.         {
  51.             if (item == int.MinValue)
  52.             {
  53.                 continue;
  54.             }
  55.             Console.Write(item);
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment