jabela

Untitled

Jul 6th, 2024 (edited)
746
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.86 KB | None | 0 0
  1. public class QuickSortExample {
  2.  
  3.     // Method to partition the array
  4.     public static int partition(int[] array, int low, int high) {
  5.         int pivot = array[high]; // Choosing the last element as the pivot
  6.         int i = (low - 1); // Index of smaller element
  7.  
  8.         for (int j = low; j < high; j++) {
  9.             // If the current element is smaller than or equal to the pivot
  10.             if (array[j] <= pivot) {
  11.                 i++;
  12.  
  13.                 // Swap array[i] and array[j]
  14.                 int temp = array[i];
  15.                 array[i] = array[j];
  16.                 array[j] = temp;
  17.             }
  18.         }
  19.  
  20.         // Swap array[i + 1] and array[high] (or pivot)
  21.         int temp = array[i + 1];
  22.         array[i + 1] = array[high];
  23.         array[high] = temp;
  24.  
  25.         return i + 1;
  26.     }
  27.  
  28.     // Method to perform quicksort
  29.     public static void quickSort(int[] array, int low, int high) {
  30.         if (low < high) {
  31.             // Partition the array around the pivot and get the pivot index
  32.             int pi = partition(array, low, high);
  33.  
  34.             // Recursively sort the sub-arrays
  35.             quickSort(array, low, pi - 1); // Sort the left sub-array
  36.             quickSort(array, pi + 1, high); // Sort the right sub-array
  37.         }
  38.     }
  39.  
  40.     // Main method to demonstrate quicksort
  41.     public static void main(String[] args) {
  42.         int[] array = {10, 7, 8, 9, 1, 5};
  43.         int n = array.length;
  44.  
  45.         System.out.println("Original array:");
  46.         printArray(array);
  47.  
  48.         quickSort(array, 0, n - 1);
  49.  
  50.         System.out.println("Sorted array:");
  51.         printArray(array);
  52.     }
  53.  
  54.     // Method to print the array
  55.     public static void printArray(int[] array) {
  56.         for (int i = 0; i < array.length; i++) {
  57.             System.out.print(array[i] + " ");
  58.         }
  59.         System.out.println();
  60.     }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment