thorax232

Java - Cocktail Sort

Nov 13th, 2013
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.61 KB | None | 0 0
  1. public static long cocktailSort(int[] list) {
  2.     int begin = -1;
  3.     int end = list.length - 2;
  4.     boolean swapped = false;
  5.     int temp;
  6.        
  7.     do {
  8.         swapped = false;
  9.         begin += 1;
  10.         for(int i = begin; i < end; i++) {
  11.             if(list[i] > list[i + 1]) {
  12.                 temp = list[i];
  13.                 list[i] = list[i + 1];
  14.                 list[i + 1] = temp;
  15.                 swapped = true;
  16.             }
  17.         }
  18.            
  19.         if(!swapped) {
  20.             end -= 1;
  21.             for(int i = end; i > begin; i--) {
  22.                 if(list[i] > list[i + 1]) {
  23.                     temp = list[i];
  24.                     list[i] = list[i + 1];
  25.                     list[i + 1] = temp;
  26.                     swapped = true;
  27.                 }
  28.             }
  29.         }
  30.     } while(swapped);
  31.        
  32.     return list;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment