[Java] Java implementation of selection sort

Brief

Selection sort is a simple sorting algorithm, which processes are as follows:
① find the smallest array element
② the first element of the array and its exchange
③ find the smallest element in the rest of the element
④ it and arrays a second switching element for
the next and so forth, until the entire array are ordered

example

Next we look at a specific example:
using the selected sorting array {S, O, R, T , E, X, A, M, P, L, E} ordered
Tips: i indicates the sort min represents the minimum number of index elements
I min. 1 0 2. 3. 4. 5. 6. 7. 8. 9 10
      S O R & lt T a M P L E E X-
0. 6 X-S O R & lt T E a M P L E
. 1. 4   O R T  X S M P L E
2  10 A E R T O X S M P L 
3  9  A And E T O X S M P  R
4  7  A And E L O X S  P T R
5  7  A E E L M X S  P T R
6  8  A E L E M O S X  T R
7  10 A E E L M O P X S T 
8  8  A E E L M O P R  T X
9  9  A E E L M O P R S T X
10 10 A E E L M O P R S T X-
---------------------------
sorting is done: A E E L M O P R S T X

Code Display

package Sort;

import java.util.*;

public class Selection_Sort {
	//选择排序
	public static void sort(Comparable[] a) {
		int N = a.length;
		for (int i = 0; i < N; i++) {
			//将a[i]和a[i+1]到a[N]中的最小元素作交换
			int min = i;
			for (int j = i+1; j<N; j++) {
				if ( a[j].compareTo(a[min]) < 0 )//如果a[j]<a[min]
					min = j;
			}
			//将a[i]和a[min]调换位置
			Comparable t = a[i];
			a[i] = a[min];
			a[min] = t;
		}
	}
	
	//用于打印展示数组的方法
	private static void show(Comparable[] a) {
		for (int i = 0; i<a.length; i++)
			System.out.print(a[i]+" ");
		System.out.println();
	}
	
	//用例
	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		String in = reader.nextLine();
		String[] a = in.split(" ");
		sort(a);//调用上面的选择排序方法
		show(a);
	}
}

Input output
Input:
2,233,441,166,558,877
output:
1,122,334,455,667,788

Sort success!

Released two original articles · won praise 0 · Views 21

Guess you like

Origin blog.csdn.net/weixin_45434953/article/details/104238633