Advertisement
claukiller

Untitled

Mar 2nd, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. package labs.course15_16.lab2;
  2.  
  3. /* This program can be used to sort n elements with
  4. * the best algorithm. It is the QUICKSORT */
  5. public class QuicksortCentralElement
  6. {
  7. static int []v;
  8.  
  9. public static void main (String arg [] ){
  10. int n= Integer.parseInt (arg[0]); //size of the problem
  11. v = new int [n];
  12.  
  13. Vector.sorted(v);
  14. System.out.println("VECTOR TO BE SORTED:");
  15. Vector.write(v);
  16. quicksort(v);
  17. System.out.println("SORTED VECTOR:");
  18. Vector.write(v);
  19.  
  20. Vector.inverselySorted (v);
  21. System.out.println("VECTOR TO BE SORTED:");
  22. Vector.write(v);
  23. quicksort(v);
  24. System.out.println("SORTED VECTOR:");
  25. Vector.write(v);
  26.  
  27. Vector.random(v, 1000000);
  28. System.out.println("VECTOR TO BE SORTED:");
  29. Vector.write(v);
  30. quicksort(v);
  31. System.out.println("SORTED VECTOR:");
  32. Vector.write(v);
  33.  
  34. }
  35.  
  36.  
  37.  
  38. private static void quickSort(int elements[], int left, int right){
  39. int i = left;
  40. int j = right-1;
  41. int pivot;
  42.  
  43. if (left < right){
  44. int center = (left+right)/2;
  45. if((right-left) >=3){
  46. pivot = elements[center];
  47. Util.interchange(elements, center, right);
  48. do{
  49. while (elements[i] <= pivot && i <right) i++; //first element > pivot
  50. while (elements[j] >=pivot && j>left) j--; //first elements < pivot
  51. if (i<j) Util.interchange(elements, i, j);
  52. } while (i < j);
  53. //set position of the pivot
  54. Util.interchange(elements, i, right);
  55. quickSort(elements, left, i-1);
  56. quickSort(elements, i+1, right);
  57. }
  58. }
  59. }
  60.  
  61. public static void quicksort(int[] elements) {
  62. quickSort(elements, 0, elements.length-1);
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement