Advertisement
Guest User

QuickSort

a guest
Jan 14th, 2013
1,196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.33 KB | None | 0 0
  1. using System;
  2.  
  3. namespace QuickSortTest
  4. {
  5.     class MainClass
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             // Create an unsorted array of string elements
  10.             string[] unsorted = { "1","2","3","4","5","6","7","8","9" };
  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.             Console.ReadLine();
  32.         }
  33.        
  34.         public static void Quicksort(IComparable[] elements, int left, int right)
  35.         {
  36.             int i = left, j = right;
  37.             IComparable pivot = elements[left + (right-left)/2];
  38.            
  39.             while (i <= j)
  40.             {
  41.                 while (elements[i].CompareTo(pivot) < 0)
  42.                 {
  43.                     i++;
  44.                 }
  45.                
  46.                 while (elements[j].CompareTo(pivot) > 0)
  47.                 {
  48.                     j--;
  49.                 }
  50.                
  51.                 if (i <= j)
  52.                 {
  53.                     // Swap
  54.                     IComparable tmp = elements[i];
  55.                     elements[i] = elements[j];
  56.                     elements[j] = tmp;
  57.                    
  58.                     i++;
  59.                     j--;
  60.                 }
  61.             }
  62.            
  63.             // Recursive calls
  64.             if (left < j)
  65.             {
  66.                 Quicksort(elements, left, j);
  67.             }
  68.            
  69.             if (i < right)
  70.             {
  71.                 Quicksort(elements, i, right);
  72.             }
  73.         }
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement