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

8 篇文章 0 订阅

以下是二分排序的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]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值