fork download
  1. // C# program for implementation of QuickSort
  2. using System;
  3.  
  4. class GFG {
  5.  
  6. /* This function takes last element as pivot,
  7. places the pivot element at its correct
  8. position in sorted array, and places all
  9. smaller (smaller than pivot) to left of
  10. pivot and all greater elements to right
  11. of pivot */
  12. static int partition(int []arr, int low,
  13. int high)
  14. {
  15. int pivot = arr[high];
  16.  
  17. // index of smaller element
  18. int i = (low - 1);
  19. for (int j = low; j < high; j++)
  20. {
  21. // If current element is smaller
  22. // than the pivot
  23. if (arr[j] < pivot)
  24. {
  25. i++;
  26.  
  27. // swap arr[i] and arr[j]
  28. int temp = arr[i];
  29. arr[i] = arr[j];
  30. arr[j] = temp;
  31. }
  32. }
  33.  
  34. // swap arr[i+1] and arr[high] (or pivot)
  35. int temp1 = arr[i+1];
  36. arr[i+1] = arr[high];
  37. arr[high] = temp1;
  38.  
  39. return i+1;
  40. }
  41.  
  42.  
  43. /* The main function that implements QuickSort()
  44. arr[] --> Array to be sorted,
  45. low --> Starting index,
  46. high --> Ending index */
  47. static void quickSort(int []arr, int low, int high)
  48. {
  49. if (low < high)
  50. {
  51.  
  52. /* pi is partitioning index, arr[pi] is
  53. now at right place */
  54. int pi = partition(arr, low, high);
  55.  
  56. // Recursively sort elements before
  57. // partition and after partition
  58. quickSort(arr, low, pi-1);
  59. quickSort(arr, pi+1, high);
  60. }
  61. }
  62.  
  63. // A utility function to print array of size n
  64. static void printArray(int []arr, int n)
  65. {
  66. for (int i = 0; i < n; ++i)
  67. Console.Write(arr[i] + " ");
  68.  
  69. Console.WriteLine();
  70. }
  71.  
  72. // Driver program
  73. public static void Main()
  74. {
  75. int []arr = {10, 7, 8, 9, 1, 5};
  76. int n = arr.Length;
  77. quickSort(arr, 0, n-1);
  78. Console.WriteLine("sorted array ");
  79. printArray(arr, n);
  80. }
  81. }
  82.  
  83. // This code is contributed by Sam007.
  84.  
Success #stdin #stdout 0.02s 16040KB
stdin
Standard input is empty
stdout
sorted array 
1 5 7 8 9 10