Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. // basic implementation, where pivot is the first element
  2. function quickSortBasic(array) {
  3. if(array.length < 2) {
  4. return array;
  5. }
  6.  
  7. var pivot = array[0];
  8. var lesserArray = [];
  9. var greaterArray = [];
  10.  
  11. for (var i = 1; i < array.length; i++) {
  12. if ( array[i] > pivot ) {
  13. greaterArray.push(array[i]);
  14. } else {
  15. lesserArray.push(array[i]);
  16. }
  17. }
  18.  
  19. return quickSortBasic(lesserArray).concat(pivot, quickSortBasic(greaterArray));
  20. }
  21.  
  22. /******************* Testing Quick sort algorithm *********************/
  23.  
  24. // Returns a random integer between min (inclusive) and max (inclusive). Using Math.round() will give a non-uniform distribution, which we dont want in this case.
  25.  
  26. function getRandomInt(min, max) {
  27. return Math.floor(Math.random() * (max - min + 1)) + min;
  28. // By adding 1, I am making the maximum inclusive ( the minimum is inclusive anyway). Because, the Math.random() function returns a floating-point, pseudo-random number in the range from 0 inclusive up to but not including 1
  29. }
  30.  
  31. var arr = [];
  32.  
  33. for (var i = 0; i < 10; i++) { //initialize a random integer unsorted array
  34. arr.push(getRandomInt(1, 100));
  35. }
  36.  
  37. console.log("Unsorted array: ");
  38. console.log(arr); //printing unsorted array
  39.  
  40. arr = quickSortBasic(arr, 0, arr.length - 1);
  41. console.log("Sorted array: ");
  42. console.log(arr);
  43.  
  44. /* Output -
  45. Unsorted array:
  46. [ 63, 95, 63, 26, 76, 19, 65, 8, 63, 26 ]
  47. Sorted array:
  48. [ 8, 19, 26, 26, 63, 63, 63, 65, 76, 95 ]
  49. [Finished in 0.1s]
  50. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement