Advertisement
Teodor92

Arrays.14.QuickSort

Jan 21st, 2013
333
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.30 KB | None | 0 0
  1. /* Write a program that sorts an array
  2.  * of strings using the quick sort
  3.  * algorithm (find it in Wikipedia).
  4.  */
  5.  
  6. using System;
  7. using System.Collections.Generic;
  8.  
  9. class QuickSort
  10. {
  11.     static List<int> QuickSortEmpement(List<int> unsortedList)
  12.     {
  13.         if (unsortedList.Count <= 1)
  14.         {
  15.             return unsortedList;
  16.         }
  17.         int pivot = unsortedList.Count / 2;
  18.         int pivotValue = unsortedList[pivot];
  19.         unsortedList.RemoveAt(pivot);
  20.         List<int> lesser = new List<int>();
  21.         List<int> greater = new List<int>();
  22.         foreach (int element in unsortedList)
  23.         {
  24.             if (element <= pivotValue)
  25.             {
  26.                 lesser.Add(element);
  27.             }
  28.             else
  29.             {
  30.                 greater.Add(element);
  31.             }
  32.         }
  33.         List<int> result = new List<int>();
  34.         result.AddRange(QuickSortEmpement(lesser));
  35.         result.Add(pivotValue);
  36.         result.AddRange(QuickSortEmpement(greater));
  37.         return result;
  38.  
  39.     }
  40.     static void Main()
  41.     {
  42.         List<int> array = new List<int> { 2, 3, 5, 0, 123, 3, 23, 1234, 87 };
  43.         List<int> sortedArray = QuickSortEmpement(array);
  44.         foreach (var item in sortedArray)
  45.         {
  46.             Console.Write("{0} ",item);
  47.         }
  48.         Console.WriteLine();
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement