Advertisement
Klaxon

[C# Arrays] Quick Sort Algorithm

Sep 30th, 2013
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. // 14. Write a program that sorts an array of strings using the quick sort algorithm (find it in Wikipedia).
  2.  
  3. using System;
  4.  
  5. class QuickSort // I use help for this! (Wikipedia)
  6. {
  7.     static void Main()
  8.     {
  9.         // Get the size
  10.         Console.Write("Enter array size: ");
  11.         int n = int.Parse(Console.ReadLine());
  12.         string[] input = new string[n];
  13.  
  14.         // Get the input
  15.         for (int i = 0; i < n; i++)
  16.         {
  17.             Console.Write("Index {0}: ", i);
  18.             input[i] = Console.ReadLine();
  19.         }
  20.         Console.WriteLine();
  21.  
  22.         // Sort the array
  23.         QuickSortAlgorithm(input, 0, input.Length - 1);
  24.  
  25.         // Print sorted array
  26.         for (int i = 0; i < n; i++)
  27.         {
  28.             if (i == n - 1)
  29.             {
  30.                 Console.WriteLine("{0}", input[i]);
  31.             }
  32.             else
  33.             {
  34.                 Console.Write("{0}, ", input[i]);
  35.             }
  36.         }
  37.     }
  38.  
  39.     // Quick sort algorithm main magic
  40.     public static void QuickSortAlgorithm(IComparable[] elements, int left, int right)
  41.     {
  42.         int i = left;
  43.         int j = right;
  44.         IComparable pivot = elements[(left + right) / 2];
  45.  
  46.         while (i <= j)
  47.         {
  48.             while (elements[i].CompareTo(pivot) < 0)
  49.             {
  50.                 i++;
  51.             }
  52.             while (elements[j].CompareTo(pivot) > 0)
  53.             {
  54.                 j--;
  55.             }
  56.             if (i <= j)
  57.             {
  58.                 // swap
  59.                 IComparable temp = elements[i];
  60.                 elements[i] = elements[j];
  61.                 elements[j] = temp;
  62.  
  63.                 i++;
  64.                 j--;
  65.             }
  66.         }
  67.  
  68.         // Recursive calls
  69.         if (left < j)
  70.         {
  71.             QuickSortAlgorithm(elements, left, j);
  72.         }
  73.         if (i < right)
  74.         {
  75.             QuickSortAlgorithm(elements, i, right);
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement