Quick Sort
unknown
java
19 days ago
1.3 kB
3
Indexable
import java.util.*; class Solution { private static int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] <= pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } public static void quickSort(int[] arr, int low, int high) { if (low >= high) return; int p = partition(arr, low, high); quickSort(arr, low, p - 1); quickSort(arr, p + 1, high); } } public class tUf { public static void main(String args[]) { int n = 7; int arr[] = {9, 4, 7, 6, 3, 1, 5}; System.out.println("Before sorting array: "); for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println(); Solution.quickSort(arr, 0, n - 1); System.out.println("After sorting array: "); for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println(); } }
Editor is loading...
Leave a Comment