Custopootimus

Small Optimized Bubble Sort

Sep 29th, 2012
428
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. //Short and Fast (10 Lines)
  2. private static int[] bubbleSort(int[] sort) {
  3.     int i, x=sort.length;
  4.     for(boolean again = true; again;)
  5.         for (x--, i = 1, again = false; i < x; i++)
  6.             if (sort[i-1]>sort[i]) {
  7.                 int t = sort[i-1];
  8.                 sort[i-1] = sort[i];
  9.                 sort[i]=t;
  10.                 again=true;
  11.             }
  12.     return sort;
  13. }
  14.  
  15. //Just really short. (7 Lines)
  16. private static int[] bubbleSort(int[] sort) {
  17.     for(int i, x=sort.length, a=1; a==1;)
  18.         for (x--, i = 1, a = 0; i < x; i++)
  19.             if (sort[i-1]>sort[i]) {
  20.                 sort[i]=(sort[i-1]^=sort[i]^=sort[i-1])^sort[i];
  21.                 a=1;
  22.             }
  23.     return sort;
  24. }
  25.  
  26. //Even smaller! (5 lines)
  27. private static int[] bubbleSort(int[] sort) {
  28.     for(int i, a=1, x=sort.length+1; a==1;)
  29.         for (x--, i = 1, a = 0; i < x; i++)
  30.             for(;sort[i-1]>sort[i];a=1)
  31.                 sort[i]=(sort[i-1]^=sort[i]^=sort[i-1])^sort[i];
  32.     return sort;
  33. }
  34.  
  35. //And finally, in four lines:
  36. private static int[] bubbleSort(int[] sort) {
  37.     for(int i, t, a=1, x=sort.length; a==1; x--)
  38.         for (i=1, a=0; i < x; i++)
  39.             for(a=1; (t=sort[i-1]) > sort[i]; sort[i-1]=sort[i], sort[i]=t);
  40.     return sort;
  41. }
  42.  
  43. //DO NOT USE, IN PROGRESS:
  44. private static int[] bubbleSort(int[] sort, int l) {
  45.     for (int i=1;i<l;i++)
  46.         for(int t=sort[i-1];sort[i-1]>sort[i];sort[i-1]=sort[i],sort[i]=t,bubbleSort(sort, l--));
  47.     return sort;
  48. }
  49. //This would be called using this: bubbleSort(unsorted, unsorted.length);
Advertisement
Add Comment
Please, Sign In to add comment