Advertisement
grubcho

Largest N Elements - buble and insertion

Jun 29th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.11 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. //Read a list of integers on the first line of the console. On the next line, you will receive an integer N. After that, find and print //the largest N elements the array, sorted in descending order.
  7. //namespace LargestNElements
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             int[] array = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
  14.             int n = int.Parse(Console.ReadLine());
  15.  
  16.             //BubbleSort(array);
  17.             InsertionSort(array);
  18.             List<int> largestN = new List<int>();
  19.             for (int i = 0; i < n; i++)
  20.             {
  21.                 largestN.Add(array[i]);
  22.             }
  23.             Console.WriteLine(string.Join(" ", largestN));
  24.         }
  25.         //static void BubbleSort(int[] array)
  26.         //{
  27.             //bool swapped;
  28.             //do
  29.             //{
  30.                 //swapped = false;
  31.                 //for (int i = 0; i < array.Length-1; i++)
  32.                 //{
  33.                     //if (array[i] < array[i+1])
  34.                     //{
  35.                         //Swap(ref array[i], ref array[i+1]);
  36.                         //swapped = true;
  37.                     //}
  38.                 //}
  39.  
  40.             //} while (swapped);
  41.         //}
  42.         static void InsertionSort(int[] array)
  43.         {
  44.             for (int firstIndex = 0; firstIndex < array.Length; firstIndex++)
  45.             {
  46.                 for (int secondIndex = firstIndex; secondIndex > 0; secondIndex--)
  47.                 {
  48.                     if (array[secondIndex-1] < array[secondIndex])
  49.                     {
  50.                         Swap(ref array[secondIndex - 1], ref array[secondIndex]);
  51.                     }
  52.                     else
  53.                     {
  54.                         break;
  55.                     }
  56.                 }
  57.             }
  58.         }
  59.         static void Swap(ref int num1, ref int num2)
  60.         {
  61.             int temp = num1;
  62.             num1 = num2;
  63.             num2 = temp;
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement