BubaLazi

04. Sort Array Using Bubble Sort

Jul 18th, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.15 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.  
  7. namespace ArraysAndLists
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
  14.             BubbleSort(arr);
  15.             Console.WriteLine(string.Join(" ", arr));
  16.         }        
  17.  
  18.         static void BubbleSort(int[] arr)
  19.         {
  20.             while(true)
  21.             {
  22.                 bool swapped = false;
  23.                 for (int index = 0; index < arr.Length - 1; index++)
  24.                 {
  25.                     if (arr[index] > arr[index + 1])
  26.                     {
  27.                         Swap(ref arr[index], ref arr[index + 1]);
  28.                         swapped = true;
  29.                     }
  30.                 }
  31.                 if(!swapped)
  32.                 {
  33.                     break;
  34.                 }
  35.             }            
  36.         }
  37.  
  38.         static void Swap(ref int first,ref int second)
  39.         {
  40.             int temp = first;
  41.             first = second;
  42.             second = temp;
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment