Wonkiest29

Untitled

Nov 14th, 2025
523
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class QuickSort {
  4.  
  5. public static void main(String[] args) {
  6. int[] array = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
  7. System.out.println("Before:");
  8. System.out.println(Arrays.toString(array));
  9.  
  10. quickSort(array, 0, array.length - 1);
  11.  
  12. System.out.println("After:");
  13. System.out.println(Arrays.toString(array));
  14. }
  15.  
  16. public static void quickSort(int[] array, int low, int high) {
  17. // Base case: if array has less than 2 elements, it's already sorted
  18. if (low >= high) {
  19. return;
  20. }
  21.  
  22. // Partition the array and get the pivot index
  23. int pivotIndex = partition(array, low, high);
  24.  
  25. // Recursively sort left part (before pivot)
  26. quickSort(array, low, pivotIndex - 1);
  27.  
  28. // Recursively sort right part (after pivot)
  29. quickSort(array, pivotIndex + 1, high);
  30. }
  31.  
  32. public static int partition(int[] array, int low, int high) {
  33. // Select the last element as pivot
  34. int pivot = array[high];
  35.  
  36. // Index for smaller element (where pivot will be placed)
  37. int i = low - 1;
  38.  
  39. // Walk through array comparing elements with pivot
  40. for (int j = low; j < high; j++) {
  41. // If current element is smaller than or equal to pivot
  42. if (array[j] <= pivot) {
  43. i++;
  44. // Swap elements: place smaller element to the left
  45. int temp = array[i];
  46. array[i] = array[j];
  47. array[j] = temp;
  48. }
  49. }
  50.  
  51. // Place pivot in its correct position
  52. i++;
  53. int temp = array[i];
  54. array[i] = array[high];
  55. array[high] = temp;
  56.  
  57. // Return pivot index
  58. return i;
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment