Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class QuickSortArrayOfStrings
- {
- static void Main()
- {
- //Write a program that sorts an array of strings using the quick sort algorithm (find it in Wikipedia).
- //Initialize the string list for sort
- List <string> stringList = new List<string>{"home", "space", "room", "sofa", "lamp", "furniture", "bed", "book", "bookshelf" };
- //Call the Partition method
- stringList = Partition(stringList);
- //Print the result on the console
- foreach (string item in stringList)
- {
- Console.WriteLine("{0} ", item);
- }
- }
- static List<string> Partition(List<string> partitionList)
- {
- List<string> beforePivot = new List<string>(); //A list for the elements before the pivot
- List<string> afterPivot = new List<string>();//A list for the elements after the pivot
- if (partitionList.Count > 0)
- {
- int pivotIndex = partitionList.Count / 2; //Different possibilities here. I take the middle element
- string pivotString = partitionList[pivotIndex]; //Keep the pivot element so that we could generate the new partition list
- for (int i = 0; i < partitionList.Count; i++)
- {
- if (i != pivotIndex)
- {
- if (string.Compare(partitionList[i], pivotString) <= 0) //compare the current string to the pivot one and add it to the correct partition
- {
- beforePivot.Add(partitionList[i]);
- }
- else
- {
- afterPivot.Add(partitionList[i]);
- }
- }
- }
- beforePivot = Partition(beforePivot);
- afterPivot = Partition(afterPivot);
- partitionList.Clear();
- partitionList.AddRange(beforePivot);
- partitionList.Add(pivotString);
- partitionList.AddRange(afterPivot);
- }
- return partitionList;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement