算法(1) 选择排序算法 java

简介:选择排序是一个时间复杂度为O(N^2)的基本排序算法,当然也有其适用的场景,比如说该算法的易于实现的特性,可应用于对某些实际问题的快速实现上.

原理:从未排序的数据中,选出最小的数据,然后与未排序的第一个数据进行比较交换操作,直到所有的数据都排好序.

步骤:

①在未进行排序的数据中,寻找到最小的数据,假设为A,并记录下该下标

②用未排序的第一个数据B与从①中得到的数据A进行比较,如果A小于B,则交换AB,否则不交换.

③重复以上的①②步骤,直到所有的数据都排好序.

 

代码是思路的体现,因此在写代码之前一定要理清楚思路.

/**
 * 规则 [0,i-1] 采用前闭后闭的原则进行算法的编写,牢记. 顺序为 从小到大排序
 * 
 * @author JamesWang
 *
 */
public class SelectionSort implements IPerformance {
	private int[] arr;
	public SelectionSort(int[] arr) {
		this.arr = arr;
	}
	
	@Override
	public void performance() {
		int minIndex;
		for (int i = 0; i <= arr.length - 1; i++) {// [0,arr.length - 1] 前闭 后闭
			minIndex = i;// 默认当前i为最小值的下标
			for (int j = i + 1; j <= arr.length - 1; j++) {
				if (arr[j] < arr[minIndex]) {
					minIndex = j;
				}
			}
			//进行比较交换操作
			if(arr[minIndex] != arr[i]) {//只有当两个下标对应的值不相等再进行交换
				arr[i] = arr[i] + arr[minIndex];
				arr[minIndex] = arr[i] - arr[minIndex];
				arr[i] = arr[i] - arr[minIndex];
			}
		}
	}
	
	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) {
		int[] arr = SortUtils.createArray(100);//创建一个数值范围为[0,100)包含有100个元素的数组
		PerformanceUtils performanceUtils = new PerformanceUtils(new SelectionSort(arr));//创建代理类
		performanceUtils.performance();//执行代理方法
		System.out.println(SortUtils.getString(arr));
	}
}

public interface IPerformance {
	public void performance();
}

public class SortUtils {
	public static int[] createArray(int count) {
		int[] arr = new int[count];
		Random random = new Random();
		for (int index = 0; index < count; index++) {
			arr[index] = random.nextInt(count);
		}
		return arr;
	}
	
	public static int[] copy(int[] arr) {
		return Arrays.copyOf(arr, arr.length);
		
	}
	
	public static String getString(int[] arr) {
		StringBuffer sb = new StringBuffer();
		for(int a : arr) {
			sb.append( a + ",");
		}
		return sb.toString();
	}
	
}

/**
 * 使用代理模式来进行性能的测试
 * 
 * @author JamesWang Create on 2018年1月4日 下午4:05:35
 */
public class PerformanceUtils implements IPerformance {
	private IPerformance performance;

	public PerformanceUtils(IPerformance performance) {
		this.performance = performance;
	}

	@Override
	public void performance() {
		long startTime = System.currentTimeMillis();
		performance.performance();
		System.out.println("运行时间为:" + (System.currentTimeMillis() - startTime) + "毫秒");
	}

}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值