Java二分排序算法简易版(原创)

xiaoxiao2021-02-28  44

以下是二分排序的Java代码,排序的图片抽空我再发上去

package algorithm; import java.util.Arrays; /** * @author shany */ public class SY_erfen { // 因为int型数组是常量,所以两个数组指向地址相同 // 两个数组操作的都是一个对象,所以每次都要为temp开辟新空间 // 要排序的原数组 static int[] arr; // 参与排序的数组 static int[] temp; // 将数组二分,直到两个数组中一个数组长度为1为止 public void erfen(int start, int end) { if (start < end) { erfen(start, (end + start) / 2); erfen((end + start) / 2 + 1, end); hebin(start, end); //看每一轮数据的变化情况 System.out.println(Arrays.toString(arr)); } } // 将两个数组合并,排序 public void hebin(int start, int end) { temp = new int[arr.length]; int left_index = start; int right_index = (end + start) / 2 + 1; int index = start; while (true) { // 如果光标左边大于光标右边 if (arr[left_index] > arr[right_index]) { temp[index++] = arr[right_index++]; } else { temp[index++] = arr[left_index++]; } // 如果左边数组取到最后一位 if (left_index == (end + start) / 2 + 1) { System.arraycopy(arr, right_index, temp, index, end - right_index + 1); break; } // 如果右边数组取到最后一位 if (right_index == end + 1) { System.arraycopy(arr, left_index, temp, index, (end + start) / 2 - left_index + 1); break; } } //将排序后的数据写回原数组 System.arraycopy(temp, start, arr, start, end - start + 1); } public SY_erfen(int[] arrs) { super(); // 将数据传给静态变量arr arr = arrs; // 调用排序算法 erfen(0, arr.length - 1); // 输出程序运行结果 System.out.println(Arrays.toString(arr)); } // main方法 public static void main(String[] args) { int arrs[] = { 5, 4, 10, 8, 7, 9, 11, 13, 12, 15, 14 }; new SY_erfen(arrs); } }

以下是程序运行的结果

[4, 5, 10, 8, 7, 9, 11, 13, 12, 15, 14] [4, 5, 10, 8, 7, 9, 11, 13, 12, 15, 14] [4, 5, 10, 7, 8, 9, 11, 13, 12, 15, 14] [4, 5, 10, 7, 8, 9, 11, 13, 12, 15, 14] [4, 5, 7, 8, 9, 10, 11, 13, 12, 15, 14] [4, 5, 7, 8, 9, 10, 11, 13, 12, 15, 14] [4, 5, 7, 8, 9, 10, 11, 12, 13, 15, 14] [4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15] [4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15] [4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15] [4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15]
转载请注明原文地址: https://www.6miu.com/read-2631273.html

最新回复(0)