Sorting Algorithm (B) - Selection Sort Method

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/A1344714150/article/details/88636169

Goal: to achieve selection sort, the array elements are sorted in ascending

Custom method selectionSort, its argument is to be sorted array array, return the sorted array is completed.

Ideas: the use of i from 0 to traverse the array array.length-1, traversal, a minimum recording minIndex subscript variable, minIndex initial value of i; j variable then use the array subscript i + 1 ~ array .length-1 element is traversed during the traversal of the array [J] and array [minIndex] are compared, if the array [J] is less than the array [minIndex], assigned to the minIndex j, this layer after traversal of array [minIndex] and array [i] exchange, so the minimum number of array exchanged to the front.

Simple, selected sorting method is the order of each iteration, the smallest element in the front to traverse the range mentioned.

Code:

	//选择排序
	public static void selectionSort(int[] array){
		for(int i=0;i<array.length;i++){
			int minIndex = i;
			for(int j=i+1;j<array.length;j++){
				if(array[j]<array[minIndex]){
					minIndex = j;
				}
			}
			//交换两个数
			int temp = array[i];
			array[i] = array[minIndex];
			array[minIndex] = temp;
		}
	}

Test code:

import java.util.Scanner;

public class Client {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		int left = input.nextInt();
		int right = input.nextInt();
		int[] array = SortUtil.getRandomArrayData(n, left, right);
		System.out.println("排序前:");
		print(array);
		SortUtil.selectionSort(array);
		System.out.println("排序后:");
		print(array);
	}
	
	public static void print(int[] array){
		for(int i=0;i<array.length;i++){
			System.out.print(array[i]+" ");
		}
		System.out.println();
	}
	
}

The number of 0 to 100 20 to sort the printed results.

Guess you like

Origin blog.csdn.net/A1344714150/article/details/88636169