Advertisement
ivandrofly

Quick Sort C-Sharp/C#

Dec 24th, 2015
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.69 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Quick_sort
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             var a = new[] { 7, 6, 5, 4, 3, 2, 1, 0 };
  14.             QuickSort(a, 0, 7);
  15.  
  16.             // print sorted array
  17.             for (int i = 0; i < 8; i++)
  18.             {
  19.                 Console.Write(a[i]);
  20.             }
  21.             Console.ReadLine();
  22.         }
  23.  
  24.         private static void QuickSort(int[] a, int start, int end)
  25.         {
  26.             if (start >= end)
  27.                 return;
  28.  
  29.             // calling partition
  30.             int partitionIndex = Partition(a, start, end);
  31.             QuickSort(a, start, partitionIndex - 1);
  32.             QuickSort(a, partitionIndex + 1, end);
  33.         }
  34.  
  35.         private static int Partition(int[] a, int start, int end)
  36.         {
  37.             var pivot = a[end];
  38.             // set partition index as start initially
  39.             var partitionIndex = start;
  40.             for (int i = start; i < end; i++)
  41.             {
  42.                 if (a[i] < pivot)
  43.                 {
  44.                     // swap if element is lesser than pivot
  45.                     Swap(ref a[i], ref a[partitionIndex]);
  46.                     partitionIndex += 1;
  47.  
  48.                 }
  49.  
  50.             }
  51.             // swap pivot with element at partition index
  52.             Swap(ref a[partitionIndex], ref a[end]);
  53.             return partitionIndex;
  54.         }
  55.  
  56.         private static void Swap(ref int x, ref int y)
  57.         {
  58.             var temp = x;
  59.             x = y;
  60.             y = temp;
  61.         }
  62.     }
  63. }
  64.  
  65. // quick sort implementation c#
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement