二进制插入排序使用二进制搜索来找到正确的位置,以便在每次迭代时在特定索引处插入元素。首先,找到需要插入元素的位置。然后,将元素移动到下一个正确的位置。现在,将特定元素放置在该位置。
以下是二进制插入排序的Java代码-
public class Demo{ void Cocktail_Sort(int my_arr[]){ boolean swapped = true; int start = 0; int end = my_arr.length; while (swapped == true) { swapped = false; for (int i = start; i < end - 1; ++i) { if (my_arr[i] > my_arr[i + 1]) { int temp = my_arr[i]; my_arr[i] = my_arr[i + 1]; my_arr[i + 1] = temp; swapped = true; } } if (swapped == false) break; swapped = false; end = end - 1; for (int i = end - 1; i >= start; i--) { if (my_arr[i] > my_arr[i + 1]) { int temp = my_arr[i]; my_arr[i] = my_arr[i + 1]; my_arr[i + 1] = temp; swapped = true; } } start = start + 1; } } void print_values(int my_arr[]){ for (int i = 0; i < my_arr.length; i++) System.out.print(my_arr[i] + " "); System.out.println(); } public static void main(String[] args){ Demo my_object = new Demo(); int my_arr[] = { 6, 8, 34, 21, 0, 1, 98, 64, 6}; System.out.println("The array contains "); for (int i = 0; i < my_arr.length; i++) System.out.print(my_arr[i] + " "); System.out.println(); my_object.Cocktail_Sort(my_arr); System.out.println("The array after implementing cocktail sort is : "); my_object.print_values(my_arr); } }
输出结果
The array contains 6 8 34 21 0 1 98 64 6 The array after implementing cocktail sort is : 0 1 6 6 8 21 34 64 98