Venciity

[C#] Домашно Arrays - 14 Задача

Jan 12th, 2014
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.60 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.         Console.Write("Enter array length: ");
  43.         int n = int.Parse(Console.ReadLine());
  44.         List<int> array = new List<int>(n);
  45.  
  46.  
  47.         for (int i = 0; i < n; i++)
  48.         {
  49.             Console.Write("Insert element {0} = ", i + 1);
  50.             int g = int.Parse(Console.ReadLine());
  51.             array.Add(g);
  52.         }
  53.  
  54.         List<int> sortedArray = QuickSortEmpement(array);
  55.         foreach (var item in sortedArray)
  56.         {
  57.             Console.Write("{0} ", item);
  58.         }
  59.         Console.WriteLine();
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment