selection sort

package com;

//selection sort
public class Selectsort {
	/*
	 * Thought:
	 * 1. Find a reference element as the minimum value (usually the first one), and subscript the array of this element to a variable min
	 * 2. Compare with other elements in turn, if there is an element smaller than it, then subscript the array of elements smaller than it to min
	 * 3. Then compare min with the initial base element subscript. If it is found to be different, it means that other elements are smaller than the base element, and the element smaller than the base element is exchanged with the base element
	*/
	
	public static void swap(int a[],int i,int index) {
		int t=a[i];
		a[i]=a[index];
		a[index]=t;
	}
	

	public  static void sort(int a[],int size) {
		for(int i=0;i<size;i++) {
			int index=i;
			for(int j=i+1;j<size;j++) {
				if(a[index]>a[j]) {
					index=j;
				}
			}
			
			if(i!=index) {//There is an element smaller than the base element
				swap(a,i,index);	
			}
			
		}
	}
	
	/*
	 * print the sorted elements
	*/
	public static void print(int a[]) {
		
		for(int i=0;i<a.length;i++) {
			
			System.out.println("The values ​​of the elements are: "+a[i]);
		}
	}
	
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int a[]= {12,23,24,21,32,45,34,25,15,2,13,21,67};
		Selectsort.sort(a,a.length-1);
		Selectsort.print(a);

	}


}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324576979&siteId=291194637