选择排序详解 (java实现)

今天翻到以前写的代码就拿出来和大家分享一些,如果有不当之处,欢迎批评指正。。

作者:王奎         博客:www.marksaas.com

选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。

选择排序的主要优点与数据移动有关。如果某个元素位于正确的最终位置上,则它不会被移动。选择排序每次交换一对元素,它们当中至少有一个将被移到其 最终位置上,因此对n个元素的表进行排序总共进行至多n-1次交换。在所有的完全依靠交换去移动元素的排序方法中,选择排序属于非常好的一种。

选择排序算法的一般策略:搜索整个值列,以找到最小值。将该值与值列中第一个位置上的值进行交换。搜索剩下的值列(第一个除外),以找到其中的最小值,然后将其与值列中第二个位置上的值进行交换。对值列中的每个位置重复该过程。在算法结束时,就完成了对值列的排序。

本文主要采用迭代法和递归发来实现。

迭代法代码:

public class SelectSort{
/*
@author mark  
@blog  www.marksaas.com
@date 2014-4-23
使用迭代选择排序,来排序数组。
*/
	public static void Sort(int[] a,int n){
		for(int index=0;index<n-1;index++){//对传入的数组进行排序,理论上只需要遍历n-1次,前n-1次
			int indexOfNextSmallest=indexOfSmallest(a,index,n-1);//找到最新的元素的数组下标
			swap(a,index,indexOfNextSmallest);//交换当前元素和最小元素
		}
	}
	public static int indexOfSmallest(int[] a,int first,int last){
		int min=a[first];//先定义一个最小值,方便记录
		int indexOfMin=first;
		for(int index=first+1;index<=last;index++){//找到最小值,并返回最小值的下标。
			if(a[index]<min){
				min=a[index];
				indexOfMin=index;
			}
		}
		return indexOfMin;
	}
	public static void swap(int[] a,int i,int j){
		int temp=a[i];//交换元素
		a[i]=a[j];
		a[j]=temp;
	}
	public static void main(String[] args){
		int[] a={2,4,1,9,45,3,6,0};
		Sort(a,a.length);
		for(int i :a){   //增强for循环,输出a中的所以元素。
			System.out.println(i);
		}
	}
}

递归选择排序:

public class SelectSort2{
	public static void sort(int[] a,int n){
		sort(a,0,n-1);
	}
	public static void sort(int[] a,int first,int last){

	if(first<last){
		int indexOfSmallMin=indexOfSmallMin(a,first,last);
		swap(a,first,indexOfSmallMin);
		sort(a,first+1,last);
		}
	}
	public static int indexOfSmallMin(int[] a,int first,int last){
		int min=a[first];
		int minIndex=first;
		for(int index=first+1;index<=last;index++){
			if(a[index]<min){
				min=a[index];
				minIndex=index;
			}
		}
		return minIndex;
	}
	public static void swap(int[] a,int i,int j){
		int temp=a[i];
		a[i]=a[j];
		a[j]=temp;
	}

	public static void main(String[]args){
		int a[]={3,54,34,23,98,45,4,5,9};
		sort(a,a.length);
		for(int i:a){
		System.out.println(i);
		}
	}
}

这两个排序方法中把int 换成Comparable,就可以比较任何实现Comparable接口的对象。由于递归法和迭代法比较相近,就没有做太多的注释,如果有不懂的地方或者有发现有问题可以通过关于本站中的联系方式联系到我。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值