Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class QuickSortExample {
- // Method to partition the array
- public static int partition(int[] array, int low, int high) {
- int pivot = array[high]; // Choosing the last element as the pivot
- int i = (low - 1); // Index of smaller element
- for (int j = low; j < high; j++) {
- // If the current element is smaller than or equal to the pivot
- if (array[j] <= pivot) {
- i++;
- // Swap array[i] and array[j]
- int temp = array[i];
- array[i] = array[j];
- array[j] = temp;
- }
- }
- // Swap array[i + 1] and array[high] (or pivot)
- int temp = array[i + 1];
- array[i + 1] = array[high];
- array[high] = temp;
- return i + 1;
- }
- // Method to perform quicksort
- public static void quickSort(int[] array, int low, int high) {
- if (low < high) {
- // Partition the array around the pivot and get the pivot index
- int pi = partition(array, low, high);
- // Recursively sort the sub-arrays
- quickSort(array, low, pi - 1); // Sort the left sub-array
- quickSort(array, pi + 1, high); // Sort the right sub-array
- }
- }
- // Main method to demonstrate quicksort
- public static void main(String[] args) {
- int[] array = {10, 7, 8, 9, 1, 5};
- int n = array.length;
- System.out.println("Original array:");
- printArray(array);
- quickSort(array, 0, n - 1);
- System.out.println("Sorted array:");
- printArray(array);
- }
- // Method to print the array
- public static void printArray(int[] array) {
- for (int i = 0; i < array.length; i++) {
- System.out.print(array[i] + " ");
- }
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment