Advertisement
Guest User

Quicksort

a guest
Apr 18th, 2015
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.91 KB | None | 0 0
  1.     public static int Partition (int[] arr, int left, int right)
  2.     {
  3.         int pivot = arr[left];
  4.         while(true)
  5.         {
  6.             while(arr[left] < pivot)
  7.             left++;
  8.    
  9.             while(arr[right] > pivot)
  10.             right--;
  11.            
  12.             if (arr[left] == pivot && arr[right] == pivot)
  13.             left++;
  14.            
  15.             if(left < right)
  16.             {
  17.                 int temp = arr[right];
  18.                 arr[right] = arr[left];
  19.                 arr[left] = temp;
  20.             }
  21.             else
  22.             return right;
  23.         }
  24.     }
  25.  
  26.    
  27.     public static void QuickSort (int[] arr, int left, int right)
  28.     {
  29.         if(left < right)
  30.         {
  31.             int pivot = Partition(arr, left, right);
  32.    
  33.             if (pivot > 1)
  34.             {
  35.                 QuickSort(arr, left, pivot - 1);
  36.             }
  37.             if (pivot + 1 < right)
  38.             {
  39.                 QuickSort(arr,pivot + 1,right);
  40.             }
  41.         }
  42.     }
  43.    
  44.     public static void Main()
  45.     {
  46.         int[] myArr = { 9, 8, 6, 5, 4, 123, 131};
  47.    
  48.         QuickSort(myArr, 0, myArr.Length - 1);
  49.         for(int i = 0; i < myArr.Length; i++)
  50.         {
  51.             Console.WriteLine(myArr[i]);
  52.         }
  53.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement