用Java实现二叉排序算法
时间: 2023-02-23 19:25:43 浏览: 100
可以参考下面的代码来实现二叉排序算法:
public class BinarySort {
public static void main(String[] args) {
int arr[] = {4, 7, 2, 1, 5, 3};
sort(arr);
System.out.print("排序后的数组:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
// 二叉排序
public static void sort(int[] arr) {
int len = arr.length;
if (len <= 1) return;
int mid = len / 2;
int[] left = Arrays.copyOfRange(arr, 0, mid);
int[] right = Arrays.copyOfRange(arr, mid, len);
sort(left);
sort(right);
merge(arr, left, right);
}
public static void merge(int[] arr, int[] left, int[] right) {
int llen = left.length;
int rlen = right.length;
int i = 0, j = 0, k = 0;
while (i < llen && j < rlen) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
}
else {
arr[k++] = right[j++];
}
}
while (i < llen) {
arr[k++] = left[i++];
}
while (j < rlen) {
arr[k++] = right[j++];
}
}
}
阅读全文