private static void SmarterBubbleSort(int[] arr, out int swaps, out int compares) { swaps = 0; compares = 0; bool swapped = true; int end = arr.Length - 1; int start = 0; //int first = 0; //int last = end; bool forwards = true; while (swapped) { swapped = false; if (forwards) { for (int i = start; i < end; i++) { compares++; if (arr[i + 1] < arr[i]) { swaps++; if (!swapped) { swapped = true; //first = (i == 0) ? 0 : (i - 1); } Swap(ref arr[i + 1], ref arr[i]); } } end--; } else { for (int i = end - 1; i >= start; i--) { compares++; if (arr[i + 1] < arr[i]) { swaps++; if (!swapped) { swapped = true; //last = i; } Swap(ref arr[i + 1], ref arr[i]); } } start++; } PostUpdate(arr); forwards = !forwards; } }