选择排序是一种简单直观的排序算法。它的工作原理是:
首先在未排序序列中找到最小元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小元素,放到排序序列的末尾。以此类推,直到所有元素排序完毕。
选择排序的交换操作介于0和n-1次之间;比较操作为n(n-1)/2之间;赋值操作介于0和3(n-1)次之间;其平均复杂度为O(n²)。
代码如下:
package book;
import java.util.Scanner;
public class JiOu {
public static void selectSort(int[] source) {
for (int i = 0; i < source.length; i++) {
for (int j = i + 1; j < source.length; j++) {
if (source[i] > source[j]) {
swap(source, i, j);
}
}
}
}
private static void swap(int[] source, int x, int y) {
int temp = source[x];
source[x] = source[y];
source[y] = temp;
}
public static void main(String[] args) {
// int[] a = {4,2,1,6,3,6,0,-5,1,1};
System.out.println("请输入数组的大小;");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] score = new int[n];
System.out.println("请输入数组的元素:");
for (int i = 0; i < score.length; i++) {
score[i] = sc.nextInt();
}
sc.close();
selectSort(score);
System.out.println("最终的排序为:");
for (int i = 0; i < score.length; i++) {
System.out.print(score[i] + " ");
}
}
}
运行结果: