Advertisement
stoianpp

QuickSort

Dec 15th, 2013
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.38 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. class QuickSortAlg
  5. {
  6.     static void Main()
  7.     {
  8.         Console.Write("Enter the array length: ");
  9.         int length = int.Parse(Console.ReadLine());
  10.         string[] myArray = new string[length];
  11.         for (int i = 0; i < length; i++)
  12.         {
  13.             Console.Write("Enter the string[{0}]: ", i + 1);
  14.             myArray[i] = Console.ReadLine();
  15.         }
  16.         QuickSort(myArray, 0, length-1);
  17.         for (int i = 0; i < length; i++)
  18.         {
  19.             Console.WriteLine(myArray[i]);
  20.         }
  21.     }
  22.  
  23.     static void QuickSort (string[] myArray, int left, int right)
  24.     {
  25.         int midIndex = (left + right) / 2;
  26.         int i = left, j = right;
  27.         while (i < j)
  28.         {
  29.             while (myArray[i].CompareTo(myArray[midIndex]) < 0) i++;
  30.             while (myArray[j].CompareTo(myArray[midIndex]) > 0) j--;
  31.             string changeString = myArray[i];
  32.             if (i <= j)
  33.             {
  34.                 myArray[i] = myArray[j];
  35.                 myArray[j] = changeString;
  36.                 i++;
  37.                 j--;
  38.             }
  39.         }
  40.         if (left < j)
  41.         {
  42.             QuickSort(myArray, left, j);
  43.         }
  44.         if (right > i)
  45.         {
  46.             QuickSort(myArray, i, right);
  47.         }
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement