- using System;
- namespace P04_QuickSort
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.Title = "Quick Sort";
- var numbers = new[] { -11, 12, -42, 0, 1, 90, 68, 6, -9 };
- Console.WriteLine("Original");
- Print(numbers);
- Sort(numbers);
- Console.WriteLine("Sorted:");
- Print(numbers);
- Console.ReadKey();
- }
- static void Swap<T>(T[] array, int i, int m)
- {
- T temp = array[i];
- array[i] = array[m];
- array[m] = temp;
- }
- static void Print<T>(T[] array)
- {
- Console.WriteLine(string.Join("\t", array));
- }
- static int Partition<T>(T[] array, int lower, int upper) where T : IComparable
- {
- var i = lower;
- var j = upper;
- T pivot = array[lower];
- do
- {
- while (array[i].CompareTo(pivot) < 0) i++;
- while (array[j].CompareTo(pivot) > 0) j--;
- if (i >= j) break;
- Swap(array, i, j);
- } while (i <= j);
- return j;
- }
- static void SubSort<T>(T[] array, int lower, int upper) where T : IComparable
- {
- if (lower < upper)
- {
- var p = Partition(array, lower, upper);
- SubSort(array, lower, p);
- SubSort(array, p + 1, upper);
- }
- }
- static void Sort<T>(T[] array) where T : IComparable
- {
- SubSort(array, 0, array.Length - 1);
- }
- }
- }
Wednesday, October 16, 2019
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment