Advertisement
ScorpS

Quick Sort

Jan 7th, 2013
756
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  1. // 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
  6. {
  7.     static void Main(string[] args)
  8.     {
  9.         // Create an unsorted array of string elements
  10.         string[] unsorted = { "z", "e", "x", "c", "m", "q", "a"};
  11.  
  12.         // Print the unsorted array
  13.         for (int i = 0; i < unsorted.Length; i++)
  14.         {
  15.             Console.Write(unsorted[i] + " ");
  16.         }
  17.  
  18.         Console.WriteLine();
  19.  
  20.         // Sort the array
  21.         Quicksort(unsorted, 0, unsorted.Length - 1);
  22.  
  23.         // Print the sorted array
  24.         for (int i = 0; i < unsorted.Length; i++)
  25.         {
  26.             Console.Write(unsorted[i] + " ");
  27.         }
  28.  
  29.         Console.WriteLine();
  30.     }
  31.  
  32.     public static void Quicksort(string[] elements, int left, int right)
  33.     {
  34.         int i = left, j = right;
  35.         string middle = elements[(left + right) / 2];
  36.  
  37.         // if you want to see whole process
  38.         //for (int k = 0; k < elements.Length; k++)
  39.         //{
  40.         //    Console.Write(elements[k] + " ");
  41.         //}
  42.         //Console.Write("\"{0}\"", middle);
  43.         //Console.WriteLine();
  44.  
  45.         while (i <= j)
  46.         {
  47.             while (elements[i].CompareTo(middle) < 0)
  48.             {
  49.                 i++;
  50.             }
  51.  
  52.             while (elements[j].CompareTo(middle) > 0)
  53.             {
  54.                 j--;
  55.             }
  56.  
  57.             if (i <= j)
  58.             {
  59.                 // Swap
  60.                 string tmp = elements[i];
  61.                 elements[i] = elements[j];
  62.                 elements[j] = tmp;
  63.  
  64.                 i++;
  65.                 j--;
  66.             }
  67.         }
  68.  
  69.         // Recursive calls
  70.         if (left < j)
  71.         {
  72.             Quicksort(elements, left, j);
  73.         }
  74.  
  75.         if (i < right)
  76.         {
  77.             Quicksort(elements, i, right);
  78.         }
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement