Quicksort Algorithm in Java


SUBMITTED BY: Guest

DATE: Oct. 25, 2013, 12:36 p.m.

FORMAT: Java

SIZE: 1.6 kB

HITS: 967

  1. import java.io.*;
  2. import java.util.*;
  3. public class QuickSort
  4. {
  5. public static void swap (int A[], int x, int y)
  6. {
  7. int temp = A[x];
  8. A[x] = A[y];
  9. A[y] = temp;
  10. }
  11. // Reorganizes the given list so all elements less than the first are
  12. // before it and all greater elements are after it.
  13. public static int partition(int A[], int f, int l)
  14. {
  15. int pivot = A[f];
  16. while (f < l)
  17. {
  18. if (A[f] == pivot || A[l] == pivot)
  19. {
  20. System.out.println("Only distinct integers allowed - C321");
  21. System.out.println("students should ignore this if statement");
  22. System.out.exit(0);
  23. }
  24. while (A[f] < pivot) f++;
  25. while (A[l] > pivot) l--;
  26. swap (A, f, l);
  27. }
  28. return f;
  29. }
  30. public static void Quicksort(int A[], int f, int l)
  31. {
  32. if (f >= l) return;
  33. int pivot_index = partition(A, f, l);
  34. Quicksort(A, f, pivot_index);
  35. Quicksort(A, pivot_index+1, l);
  36. }
  37. // Usage: java QuickSort [integer] ...
  38. // All integers must be distinct
  39. public static void main(String argv[])
  40. {
  41. int A[] = new int[argv.length];
  42. for (int i=0 ; i < argv.length ; i++)
  43. A[i] = Integer.parseInt(argv[i]);
  44. Quicksort(A, 0, argv.length-1);
  45. for (int i=0 ; i < argv.length ; i++) System.out.print(A[i] + " ");
  46. System.out.println();
  47. }
  48. }

comments powered by Disqus