Advertisement
vencinachev

BubbleSort-Special

Nov 24th, 2020
674
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.96 KB | None | 0 0
  1. using java.util;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Diagnostics;
  9.  
  10. namespace SoftSvetlina
  11. {
  12.     class Program
  13.     {
  14.         static void BubbleSort(List<int> list)
  15.         {
  16.             for (int j = 0; j < list.Count - 1; j++)
  17.             {
  18.                 bool flag = false;
  19.                 for (int i = 0; i < list.Count - j - 1; i++)
  20.                 {
  21.                     if (SumDigits(list[i]) > SumDigits(list[i + 1]) ||
  22.                         (SumDigits(list[i]) == SumDigits(list[i + 1]) && list[i] > list[i + 1]))
  23.                     {
  24.                         flag = true;
  25.                         int temp = list[i];
  26.                         list[i] = list[i + 1];
  27.                         list[i + 1] = temp;
  28.                     }
  29.                 }
  30.                 if (!flag)
  31.                 {
  32.                     break;
  33.                 }
  34.             }
  35.         }
  36.  
  37.         static int SumDigits(int number)
  38.         {
  39.             int sum = 0;
  40.             while (number != 0)
  41.             {
  42.                 sum += number % 10;
  43.                 number /= 10;
  44.             }
  45.             return sum;
  46.         }
  47.  
  48.         static void Main()
  49.         {
  50.            
  51.             List<int> nums = new List<int>();
  52.             using (StreamReader reader = new StreamReader("numbers.txt"))
  53.             {
  54.                 string line;
  55.                 while ((line = reader.ReadLine()) != null)
  56.                 {
  57.                     nums.Add(int.Parse(line));
  58.                 }
  59.             }
  60.  
  61.             BubbleSort(nums);
  62.            
  63.             Console.WriteLine(string.Join(", ", nums));
  64.  
  65.             using (StreamWriter writer = new StreamWriter("numberssort.txt"))
  66.             {
  67.                 foreach (var item in nums)
  68.                 {
  69.                     writer.WriteLine(item);
  70.                 }
  71.             }
  72.  
  73.         }
  74.     }
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement