Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2
Program: Write a program to implement quicksort in Java.
1. public class Quick
2. { 3. /* function that consider last element as pivot, 4. place the pivot at its exact position, and place 5. smaller elements to left of pivot and greater 6. elements to right of pivot. */ 7. int partition (int a[], int start, int end) 8. { 9. int pivot = a[end]; // pivot element 10. int i = (start - 1); 11. 12. for (int j = start; j <= end - 1; j++) 13. { 14. // If current element is smaller than the pivot 15. if (a[j] < pivot) 16. { 17. i++; // increment index of smaller element 18. int t = a[i]; 19. a[i] = a[j]; 20. a[j] = t; 21. } 22. } 23. int t = a[i+1]; 24. a[i+1] = a[end]; 25. a[end] = t; 26. return (i + 1); 27. } 28. 29. /* function to implement quick sort */ 30. void quick(int a[], int start, int end) 31. { 32. if (start < end) 33. { 34. int p = partition(a, start, end); //p is partitioning index 35. quick(a, start, p - 1); 36. quick(a, p + 1, end); 37. } 38. } 39. 40. /* function to print an array */ 41. void printArr(int a[], int n) 42. { 43. int i; 44. for (i = 0; i < n; i++) 45. System.out.print(a[i] + " "); 46. } 47. public static void main(String[] args) { 48. int a[] = { 13, 18, 27, 2, 19, 25 }; 49. int n = a.length; 50. System.out.println("\nBefore sorting array elements are - "); 51. Quick q1 = new Quick(); 52. q1.printArr(a, n); 53. q1.quick(a, 0, n - 1); 54. System.out.println("\nAfter sorting array elements are - "); 55. q1.printArr(a, n); 56. System.out.println(); 57. } 58. }