fork download
  1. import java.util.Scanner;
  2.  
  3. class QuickSort {
  4.  
  5. static void swap(int[] arr, int i, int j) {
  6. int temp = arr[i];
  7. arr[i] = arr[j];
  8. arr[j] = temp;
  9. }
  10.  
  11. public static int partition(int[] arr, int low, int high) {
  12. int pivot = arr[high];
  13. int i = low - 1;
  14.  
  15. for (int j = low; j < high; j++) {
  16. if (arr[j] < pivot) {
  17. i++;
  18. swap(arr, i, j);
  19. }
  20. }
  21.  
  22. swap(arr, i + 1, high);
  23. return i + 1;
  24. }
  25.  
  26. public static void quickSort(int[] arr, int low, int high) {
  27. if (low < high) {
  28. int pi = partition(arr, low, high);
  29.  
  30. quickSort(arr, low, pi - 1);
  31. quickSort(arr, pi + 1, high);
  32. }
  33. }
  34.  
  35. public static void main(String[] args) {
  36. Scanner scanner = new Scanner(System.in);
  37. System.out.print("Enter the number of elements (n): ");
  38. int n = scanner.nextInt();
  39.  
  40. int[] arr = new int[n];
  41.  
  42. System.out.println("Enter " + n + " integers separated by space or new line:");
  43. for (int i = 0; i < n; i++) {
  44. arr[i] = scanner.nextInt();
  45. }
  46. scanner.close();
  47.  
  48. quickSort(arr, 0, n - 1);
  49.  
  50. System.out.print("Sorted Array: ");
  51. for (int i = 0; i < n; i++) {
  52. System.out.print(arr[i] + " ");
  53. }
  54. System.out.println();
  55. }
  56. }
Success #stdin #stdout 0.23s 60824KB
stdin
8
12 5 8 7 4 8 9 12
stdout
Enter the number of elements (n): Enter 8 integers separated by space or new line:
Sorted Array: 4 5 7 8 8 9 12 12