Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Write a program that sorts an array of strings using the quick sort algorithm
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- class SortString
- {
- public static int CompareStrings(string s1, string s2)
- {
- //Compare two string lexicographically
- char[] first = s1.ToCharArray();
- char[] second = s2.ToCharArray();
- bool areEqual = false;
- int minLength = Math.Min(second.Length, first.Length);
- int msg = -1; //1 - s1 is smaller, 2-s2 is smaller, 0 s1 and s2 are equal
- for (int i = 0; i < minLength; i++)
- {
- if (first[i] == second[i])
- {
- msg = 0;
- areEqual = true;
- continue;
- }
- if (first[i] > second[i])
- {
- msg = 2;
- areEqual = false;
- break;
- }
- else if (first[i] < second[i])
- {
- msg = 1;
- areEqual = false;
- break;
- }
- }
- return msg;
- }
- static List<string> QuickSort(List<string> array)
- {
- //Ivaylo Kenov changed code for int list
- if (array.Count <= 1)
- {
- return array;
- }
- string pivot = array[array.Count / 2];
- List<string> less = new List<string>();
- List<string> greater = new List<string>();
- for (int i = 0; i < array.Count; i++)
- {
- if (i != (array.Count / 2))
- {
- if (CompareStrings(array[i], pivot) == 1)
- {
- less.Add(array[i]);
- }
- else
- {
- greater.Add(array[i]);
- }
- }
- }
- return ConcatenateArrays(QuickSort(less), pivot, QuickSort(greater));
- }
- static List<string> ConcatenateArrays(List<string> less, string pivot, List<string> greater)
- {
- //Ivaylo Kenov changed code for int list
- List<string> result = new List<string>();
- for (int i = 0; i < less.Count; i++)
- {
- result.Add(less[i]);
- }
- result.Add(pivot);
- for (int i = 0; i < greater.Count; i++)
- {
- result.Add(greater[i]);
- }
- return result;
- }
- static void Main(string[] args)
- {
- List<string> arrayOfIntegers = new List<string>() { "Dima", "Anna", "Ella", "Nina", "Vassil", "Pesho" };
- List<string> sortedArray = QuickSort(arrayOfIntegers);
- for (int i = 0; i < sortedArray.Count; i++)
- {
- Console.WriteLine(sortedArray[i]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement