Java二分排序算法简易版(原创)
生活随笔
收集整理的這篇文章主要介紹了
Java二分排序算法简易版(原创)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
以下是二分排序的Java代碼,排序的圖片抽空我再發(fā)上去
package algorithm;import java.util.Arrays;/*** @author shany*/public class SY_erfen {// 因?yàn)閕nt型數(shù)組是常量,所以兩個(gè)數(shù)組指向地址相同// 兩個(gè)數(shù)組操作的都是一個(gè)對象,所以每次都要為temp開辟新空間// 要排序的原數(shù)組static int[] arr;// 參與排序的數(shù)組static int[] temp;// 將數(shù)組二分,直到兩個(gè)數(shù)組中一個(gè)數(shù)組長度為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);//看每一輪數(shù)據(jù)的變化情況System.out.println(Arrays.toString(arr));}}// 將兩個(gè)數(shù)組合并,排序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) {// 如果光標(biāo)左邊大于光標(biāo)右邊if (arr[left_index] > arr[right_index]) {temp[index++] = arr[right_index++];} else {temp[index++] = arr[left_index++];}// 如果左邊數(shù)組取到最后一位if (left_index == (end + start) / 2 + 1) {System.arraycopy(arr, right_index, temp, index, end- right_index + 1);break;}// 如果右邊數(shù)組取到最后一位if (right_index == end + 1) {System.arraycopy(arr, left_index, temp, index, (end + start)/ 2 - left_index + 1);break;}}//將排序后的數(shù)據(jù)寫回原數(shù)組System.arraycopy(temp, start, arr, start, end - start + 1);}public SY_erfen(int[] arrs) {super();// 將數(shù)據(jù)傳給靜態(tài)變量arrarr = arrs;// 調(diào)用排序算法erfen(0, arr.length - 1);// 輸出程序運(yùn)行結(jié)果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);} }以下是程序運(yùn)行的結(jié)果
[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]總結(jié)
以上是生活随笔為你收集整理的Java二分排序算法简易版(原创)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Alamofire源码导读二:发起请求及
- 下一篇: 2个字节能存多少个16进制_Java语言