本文根据《大话数据结构》一书,实现了Java版的简单选择排序

更多:数据结构与算法合集 

基本思想

  简单选择排序很简单,顾名思义,即在无序序列中,每一轮选取出最小的值作为有序序列的第i个记录。

完整Java代码

(含测试代码)

import java.util.Arrays;

/**
 * 
 * @Description 简单选择排序
 *
 * @author yongh
 * @date 2018年9月15日 上午11:04:36
 */
public class SelectSort {
	/**
	 * 简单选择排序
	 */
	public void selectSort(int[] arr) {
		if (arr == null || arr.length <= 1)
			return;
		for (int i = 0; i < arr.length - 1; i++) {
			int min = i; // 最小值的下标
			for (int j = i + 1; j <= arr.length - 1; j++) {
				if (arr[j] < arr[min])
					min = j;
			}
			swap(arr, min, i);
		}
	}

	public void swap(int[] a, int i, int j) {
		int temp;
		temp = a[j];
		a[j] = a[i];
		a[i] = temp;
	}

	// =========测试代码=======
	public void test1() {
		int[] a = null;
		selectSort(a);
		System.out.println(Arrays.toString(a));
	}

	public void test2() {
		int[] a = {};
		selectSort(a);
		System.out.println(Arrays.toString(a));
	}

	public void test3() {
		int[] a = { 1 };
		selectSort(a);
		System.out.println(Arrays.toString(a));
	}

	public void test4() {
		int[] a = { 3, 3, 3, 1, 2, 1, 3, 3 };
		selectSort(a);
		System.out.println(Arrays.toString(a));
	}

	public void test5() {
		int[] a = { -3, 6, 3, 1, 3, 7, 5, 6, 2 };
		selectSort(a);
		System.out.println(Arrays.toString(a));
	}

	public static void main(String[] args) {
		SelectSort demo = new SelectSort();
		demo.test1();
		demo.test2();
		demo.test3();
		demo.test4();
		demo.test5();
	}
}

  

null
[]
[1]
[1, 1, 2, 3, 3, 3, 3, 3]
[-3, 1, 2, 3, 3, 5, 6, 6, 7]
SelectSort

相关文章:

  • 2021-10-19
  • 2022-12-23
  • 2021-05-04
  • 2021-08-11
  • 2021-09-19
  • 2021-05-13
  • 2021-08-11
  • 2022-12-23
猜你喜欢
  • 2021-08-10
  • 2021-08-04
  • 2022-01-16
  • 2022-12-23
  • 2021-05-16
  • 2021-06-24
相关资源
相似解决方案