fork(8) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.  
  11.  
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. int b[] = {10, 9, 8, 7, 7, 7, 7, 3, 2, 1};
  15. sort(b,0,b.length-1);
  16. System.out.println(Arrays.toString(b));
  17. }
  18.  
  19. static void sort(int a[], int left, int right) {
  20. if (right > left){
  21. int i=left, j=right, tmp;
  22. //we want j to be right, not right-1 since that leaves out a number during recursion
  23.  
  24. int v = a[right]; //pivot
  25.  
  26. do {
  27. while(a[i]<v)
  28. i++;
  29. while(a[j]>v)
  30. //no need to check for 0, the right condition for recursion is the 2 if statements below.
  31. j--;
  32.  
  33. if( i <= j){ //your code was i<j
  34. tmp = a[i];
  35. a[i] = a[j];
  36. a[j] = tmp;
  37. i++;
  38. j--;
  39. //we need to +/- both i,j, else it will stick at 0 or be same number
  40. }
  41. } while(i <= j); //your code was i<j, hence infinite loop on 0 case
  42.  
  43. //you had a swap here, I don't think it's needed.
  44. //this is the 2 conditions we need to avoid infinite loops
  45. // check if left < j, if it isn't, it's already sorted. Done
  46. if(left < j) sort(a,left,j);
  47. //check if i is less than right, if it isn't it's already sorted. Done
  48. // here i is now the 'middle index', the slice for divide and conquer.
  49. if(i < right) sort(a,i,right);
  50. }
  51. }
  52.  
  53.  
  54. }
Success #stdin #stdout 0.1s 320256KB
stdin
Standard input is empty
stdout
[1, 2, 3, 7, 7, 7, 7, 8, 9, 10]