Advertisement
vonko1988

QuickSort_C#

Jul 11th, 2014
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class QuickSort
  5. {
  6.     static Random randomGenerator = new Random();
  7.  
  8.     static void Main()
  9.     {
  10.         int[]  myArray = { 1, -10, -8, 7, -6, 3, 4, 5, 100, -100, 1000, 9999, 111111, -90, -60, 55, 54};
  11.  
  12.         Console.WriteLine("The original array is: ");
  13.         Console.WriteLine(String.Join(", ",  myArray));
  14.  
  15.         //in this list will be transfered the original array
  16.         List<int> myList = new List<int>();
  17.  
  18.         //put all the values from the array into the list
  19.         FillOriginalList(myArray, myList);
  20.  
  21.         int pivot = myList[myList.Count / 2];
  22.  
  23.         //process the result string to remove the exesssice spaces
  24.         string newString = Sort(myList);
  25.  
  26.         while (newString.IndexOf("  ") != -1)
  27.         {
  28.             newString = newString.Replace("  ", " ");
  29.         }
  30.  
  31.         Console.WriteLine("The arranged array is: ");
  32.         Console.WriteLine(newString);
  33.     }
  34.  
  35.     static string Sort(List<int> myList)
  36.     {
  37.         int lenList = myList.Count;
  38.  
  39.         if (lenList <= 1)
  40.         {
  41.             return String.Join(", ",  myList) + " ";
  42.         }
  43.         else
  44.         {
  45.             //Random randomGenerator = new Random();
  46.             int newPivotIndex = randomGenerator.Next(0, lenList);
  47.             int pivot =  myList[newPivotIndex];
  48.  
  49.             //here we put all elements less and equal to the pivot
  50.             List<int> less = new List<int>();
  51.             //here we put all elements bigger than the pivot
  52.             List<int> bigger = new List<int>();
  53.  
  54.             //divide the elements into the 'less' and 'bigger' lists
  55.             for (int i = 0; i < lenList; i++)
  56.             {
  57.                 if ( myList[i] < pivot)
  58.                 {
  59.                     less.Add(myList[i]);
  60.                 }
  61.                 else
  62.                 {
  63.                     bigger.Add(myList[i]);
  64.                 }
  65.             }
  66.  
  67.             return (Sort(less) + Sort(bigger));
  68.         }
  69.     }
  70.  
  71.     private static void FillOriginalList(int[] myArray, List<int> myList)
  72.     {
  73.         for (int i = 0; i < myArray.Length; i++)
  74.         {
  75.             myList.Add(myArray[i]);
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement