Advertisement
sashomaga

Quick sort algorithm

Jan 9th, 2013
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.52 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. //Write a program that sorts an array of strings using the quick sort algorithm
  4. class Program
  5. {
  6.     static void Main()
  7.     {
  8.         List<string> myList = new List<string>(new string[] { "f", "a", "b", "h", "m", "q", "c", "i", "l" });
  9.         myList = QuickSort(myList, 0, myList.Count - 1);
  10.         foreach (var item in myList)
  11.         {
  12.             Console.Write(item + " ");
  13.         }
  14.     }
  15.  
  16.     private static List<string> QuickSort(List<string> list, int left, int right)
  17.     {
  18.         int i = left;
  19.         int j = right;
  20.         string leftString = list[i];
  21.         string rightString = list[j];
  22.         string middle = list[(left + right) / 2];
  23.         //double pivotValue = ((left + right) / 2);
  24.         //string middle = a[Convert.ToInt32(pivotValue)];
  25.         string temp = null;
  26.         while (i <= j)
  27.         {
  28.             while (list[i].CompareTo(middle) < 0)
  29.             {
  30.                 i++;
  31.                 leftString = list[i];
  32.             }
  33.             while (list[j].CompareTo(middle) > 0)
  34.             {
  35.                 j--;
  36.                 rightString = list[j];
  37.             }
  38.             if (i <= j)
  39.             {
  40.                 temp = list[i];
  41.                 list[i++] = list[j];
  42.                 list[j--] = temp;
  43.             }
  44.         }
  45.         if (left < j)
  46.         {
  47.             QuickSort(list, left, j);
  48.         }
  49.         if (i < right)
  50.         {
  51.             QuickSort(list, i, right);
  52.         }
  53.         return list;
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement