天天看点

数据结构--简单排序_选择排序

原理:每一趟从待排序的记录中选出最小的元素,顺序放在已排好序的序列最后,直到全部记录排序完毕。

简单选择排序的基本思想:给定数组:int[] arr={里面n个数据};第1趟排序,在待排序数据arr[1]~arr[n]中选出最小的数据,将它与arrr[1]交换;第2趟,在待排序数据arr[2]~arr[n]中选出最小的数据,将它与r[2]交换;以此类推,第i趟在待排序数据arr[i]~arr[n]中选出最小的数据,将它与r[i]交换,直到全部排序完成。

举例:数组 int[] arr={5,2,8,4,9,1};

-------------------------------------------------------

第一趟排序: 原始数据:5  2  8  4  9  1

最小数据1,把1放在首位,也就是1和5互换位置,

排序结果:1  2  8  4  9  5

-------------------------------------------------------

第二趟排序:

第1以外的数据{2  8  4  9  5}进行比较,2最小,

排序结果:1  2  8  4  9  5

-------------------------------------------------------

第三趟排序:

除1、2以外的数据{8  4  9  5}进行比较,4最小,8和4交换

排序结果:1  2  4  8  9  5

-------------------------------------------------------

第四趟排序:

除第1、2、4以外的其他数据{8  9  5}进行比较,5最小,8和5交换

排序结果:1  2  4  5  9  8

-------------------------------------------------------

第五趟排序:

除第1、2、4、5以外的其他数据{9  8}进行比较,8最小,8和9交换

排序结果:1  2  4  5  8  9

-------------------------------------------------------

注:每一趟排序获得最小数的方法:for循环进行比较,定义一个第三个变量temp,首先前两个数比较,把较小的数放在temp中,然后用temp再去跟剩下的数据比较,如果出现比temp小的数据,就用它代替temp中原有的数据。

java代码

public class SelectSort {
	

	private long []a;
	public int elements;
	public SelectSort(int max) {
		a=new long[max];
		elements=0;
		// TODO Auto-generated constructor stub
	}
	
	public void insert(long value){
		a[elements]=value;
		elements++;
	}
	
	public void display(){
		for(int j=0;j<elements;j++)
			System.out.print(a[j]+" ");
		System.out.println();
	}
	
	public void swap(int one,int two){
		long temp=a[one];
		a[one]=a[two];
		a[two]=temp;
	}
	
	public void selectionSort(){
		int out,in,min;
		
		for(out=0;out<elements;out++)
		{
			min=out;//外层循环,假设第一个就是最小的
			for(in=out+1;in<elements;in++)//内层循环,因为比较所以从他后面的一个元素开始比较
			{
				if(a[in]<a[min]){
					min=in;
				}
					
			}
			swap(out, min);
		}
	}
	
	public static void main(String[] args) {
		int max=100;
		SelectSort selectSort=new SelectSort(max);
		selectSort.insert(123);
		selectSort.insert(21);
		selectSort.insert(234);
		selectSort.insert(322);
		selectSort.insert(23);
		
		System.out.println("没有排序:");
		selectSort.display();
		
		System.out.println("排序后");
		selectSort.selectionSort();
		selectSort.display();
	}
	
}
           

继续阅读