hamzajaved

quick sort

Dec 11th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 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.             //Quick Sort with Recursion
  14.             int[] arr = { 8, 6, 1, 4, 9, 2, 3 };
  15.             int start = 0;
  16.             int pivot = arr.Length - 1;
  17.             quick_sort(arr, start, pivot);
  18.  
  19.             foreach(var item in arr)
  20.             {
  21.                 Console.WriteLine(item);
  22.             }
  23.         }
  24.         static int partition(int []arr, int start,int pivot)
  25.         {
  26.             int i = start - 1;
  27.             for(int j= start; j<= pivot-1; j++)
  28.             {
  29.                 if(arr[j] <= arr[pivot - 1])
  30.                 {
  31.                     i = i + 1;
  32.                     int temp = arr[i];
  33.                     arr[i] = arr[j];
  34.                     arr[j] = temp;
  35.                 }
  36.             }
  37.             int tmp = arr[pivot];
  38.             arr[pivot] = arr[i + 1];
  39.             arr[i + 1] = tmp;
  40.             return i + 1;
  41.  
  42.         }
  43.         static void quick_sort(int []arr,int start,int pivot)
  44.         {
  45.             if(start <= pivot)
  46.             {
  47.                 int q = partition(arr, start, pivot);
  48.                 quick_sort(arr, start, q - 1);
  49.                 quick_sort(arr, q + 1, pivot);
  50.             }
  51.         }
  52.     }
  53. }
Add Comment
Please, Sign In to add comment