---
title: "选择排序---直接选择排序"
author: "flyer2010"
date: "2013-09-21T16:54:15Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-09-21T16:54:15Z"
id: 1944494
url: "https://flyer2010.iteye.com/blog/1944494"
---

选择排序(Selection Sort)的基本思想是：每一趟从待排序的记录中选出关键字最小的记录，顺序放在已排好序的子文件的最后，直到全部记录排序完毕。

演示地址:http://www.yxqzzx.cn/teacher/ShowArticle.asp?ArticleID=417

初始数组：
7  3  4  1  5  8

第1趟排序：
7 | 1  3  4  7  5  8

第2趟排序：
7 | 1  3  4  7  5  8

第3趟排序：
7 | 1  3  4  7  5  8

第4趟排序：
7 | 1  3  4  5  7  8

简单点说，就是从数组0位置开始遍历，找出最小的元素，将它与数组1的元素进行交换，然后从数组1位置开始遍历，找出最小的元素，将他与数组1的元素进行交换，依此类推，最后得到从小到大的数组。

```java

	/**
	 * 直接选择排序
	 * 
	 * @param unsorted
	 */
	public static void selection_sort(int[] unsorted) {
		for (int i = 0; i < unsorted.length; i++) {
			int min = unsorted[i], min_index = i;
			for (int j = i; j < unsorted.length; j++) {
				if (unsorted[j] < min) {
					min = unsorted[j];
					min_index = j;
				}
			}
			if (min_index != i) {
				int temp = unsorted[i];
				unsorted[i] = unsorted[min_index];
				unsorted[min_index] = temp;
			}
		}
	}

```