Advertisement
Guest User

Untitled

a guest
Mar 24th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. package weblab;
  2. class Solution
  3. {
  4. /**
  5. * @param array of integers to be sorted.
  6. */
  7. public static void quickSort(int[] elements){
  8.  
  9. // Base Case
  10. if(elements.length < 2) {
  11. return;
  12. }
  13. // Checks when there are only 2 elements left whether they need to be reversed.
  14. if(elements.length == 2) {
  15. if(elements[0] > elements [1]) {
  16. int temp = elements[0];
  17. elements[0] = elements[1];
  18. elements[1] = temp;
  19. }
  20. return;
  21. }
  22.  
  23. // initializes new arrays and counters.
  24. int comp = elements[elements.length - 1];
  25. int[] small = new int[elements.length];
  26. int[] large = new int[elements.length];
  27. int smallCount = 0;
  28. int largeCount = 0;
  29.  
  30. // checks whether numbers in the original array are higher or lower then comp,
  31. // then puts them into the right array
  32. for(int i = 0; i < elements.length - 1; i++) {
  33.  
  34. if(elements[i] < comp) {
  35. small[smallCount] = elements[i];
  36. smallCount++;
  37.  
  38. } else {
  39. large[largeCount] = elements[i];
  40. largeCount++;
  41. }
  42. }
  43.  
  44. //recreates the arrays made above, this time with the right length
  45. int[] smaller = new int[smallCount];
  46. for(int i = 0; i < smallCount; i++) {
  47. smaller[i] = small[i];
  48. }
  49. int[] larger = new int[largeCount];
  50. for(int i = 0; i < largeCount; i++) {
  51. larger[i] = large[i];
  52. }
  53. //recursion call for both made arrays.
  54. quickSort(smaller);
  55. quickSort(larger);
  56.  
  57. //puts the now sorted arrays back together in a single array.
  58. for(int j = 0; j < smallCount; j++) {
  59. elements[j] = smaller[j];
  60. }
  61. elements[smallCount] = comp;
  62. int m = 0;
  63. for(int k = smallCount + 1; k < smallCount + largeCount + 1; k++) {
  64. elements[k] = larger[m];
  65. m++;
  66. }
  67. }
  68. }
  69. //
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement