Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace QuickSortTest
- {
- class MainClass
- {
- static void Main(string[] args)
- {
- // Create an unsorted array of string elements
- string[] unsorted = { "1","2","3","4","5","6","7","8","9" };
- // Print the unsorted array
- for (int i = 0; i < unsorted.Length; i++)
- {
- Console.Write(unsorted[i] + " ");
- }
- Console.WriteLine();
- // Sort the array
- Quicksort(unsorted, 0, unsorted.Length - 1);
- // Print the sorted array
- for (int i = 0; i < unsorted.Length; i++)
- {
- Console.Write(unsorted[i] + " ");
- }
- Console.WriteLine();
- Console.ReadLine();
- }
- public static void Quicksort(IComparable[] elements, int left, int right)
- {
- int i = left, j = right;
- IComparable pivot = elements[left + (right-left)/2];
- while (i <= j)
- {
- while (elements[i].CompareTo(pivot) < 0)
- {
- i++;
- }
- while (elements[j].CompareTo(pivot) > 0)
- {
- j--;
- }
- if (i <= j)
- {
- // Swap
- IComparable tmp = elements[i];
- elements[i] = elements[j];
- elements[j] = tmp;
- i++;
- j--;
- }
- }
- // Recursive calls
- if (left < j)
- {
- Quicksort(elements, left, j);
- }
- if (i < right)
- {
- Quicksort(elements, i, right);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement