Advertisement
Guest User

Untitled

a guest
Dec 7th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.03 KB | None | 0 0
  1. using System;
  2.  
  3. namespace SortingAlgorithms.Sorters
  4. {
  5.     public class QuickSorter<T> : ISorter<T>
  6.         where T : IComparable<T>
  7.     {
  8.         public void Sort(T[] array)
  9.         {
  10.             if (array.Length < 10)
  11.             {
  12.                 InsertionSort(array);
  13.             }
  14.             else
  15.             {
  16.                 QuickSort(array, 0, array.Length - 1);
  17.             }
  18.         }
  19.  
  20.         private static void QuickSort(T[] array, int startIndex, int endIndex)
  21.         {
  22.             int middle = startIndex + ((endIndex - startIndex) / 2);
  23.             T pivot = array[middle];
  24.  
  25.             int left = startIndex;
  26.             int right = endIndex;
  27.  
  28.             while (left <= right)
  29.             {
  30.                 while (array[left].CompareTo(pivot) < 0)
  31.                 {
  32.                     left++;
  33.                 }
  34.  
  35.                 while (array[right].CompareTo(pivot) > 0)
  36.                 {
  37.                     right--;
  38.                 }
  39.  
  40.                 if (left <= right)
  41.                 {
  42.                     Swap(array, left, right);
  43.  
  44.                     left++;
  45.                     right--;
  46.                 }
  47.             }
  48.  
  49.             if (startIndex < right)
  50.             {
  51.                 QuickSort(array, startIndex, right);
  52.             }
  53.  
  54.             if (left < endIndex)
  55.             {
  56.                 QuickSort(array, left, endIndex);
  57.             }
  58.         }
  59.  
  60.         private static void InsertionSort(T[] array)
  61.         {
  62.             for (int i = 1; i < array.Length; i++)
  63.             {
  64.                 int index = i;
  65.                 while (index > 0 && array[index - 1].CompareTo(array[index]) > 0)
  66.                 {
  67.                     Swap(array, index - 1, index);
  68.                     index--;
  69.                 }
  70.             }
  71.         }
  72.  
  73.         private static void Swap(T[] array, int firstIndex, int secondIndex)
  74.         {
  75.             T temp = array[firstIndex];
  76.             array[firstIndex] = array[secondIndex];
  77.             array[secondIndex] = temp;
  78.         }
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement