Advertisement
grubcho

Sort Array of Strings

Jul 1st, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.41 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. //You are given an array of strings (one line, space-delimited). Sort the array using the Bubble sort or Insertion sort algorithms. //Instead of comparing if one string is smaller than the other (which you can’t do), you can use the string.CompareTo(str) method. Once //the array is sorted, print it on the console, separating the elements by spaces.
  7. //namespace Sort_array_of_strings
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             string[] array = Console.ReadLine().Split(' ').ToArray();
  14.  
  15.             BubbleSort(array);
  16.             Console.WriteLine(string.Join(" ", array));
  17.         }
  18.         static void BubbleSort(string[] array)
  19.         {
  20.             bool swapped;
  21.             do
  22.             {
  23.                 swapped = false;
  24.                 for (int i = 0; i < array.Length-1; i++)
  25.                 {
  26.                     if (array[i].CompareTo(array[i+1]) == 1)
  27.                     {
  28.                         Swap(array, i, i + 1);
  29.                         swapped = true;
  30.                     }
  31.                 }
  32.  
  33.             } while (swapped);
  34.         }
  35.         static void Swap(string[]array, int i1, int i2)
  36.         {
  37.             string temp = array[i1];
  38.             array[i1] = array[i2];
  39.             array[i2] = temp;
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement