八大排序算法之选择排序

package com.zyg.sort;

public class SelectSortAlgorithm
{
	// 选择排序
	public static void selectSort(int a[], int len)
	{
		for (int i = 0; i < len; i++)
		{
			// 设置最小元素为第i个
			int min = i;
			for (int j = i + 1; j < len; j++)
			{
				// 如果找到更小的元素,则重新设置最小元素序号
				if (a[min] > a[j])
					min = j;
			}
			// 将第i个元素与第min个元素交换
			swap(a, i, min);
		}
	}
	
	// 交换元素
	public static void swap(int a[], int i, int j)
	{
		int temp = a[i];
		a[i] = a[j];
		a[j] = temp;
	}
	
	// 打印数组
	public static void printArray(int a[])
	{
		for (int i = 0; i < a.length; i++)
		{
			System.out.println(a[i]);
		}
	}
	
	public static void main(String[] args)
	{
		// 定义初始化数组
		int a[] =
		{ 4, 3, 6, 7, 33, 15, 90, 65, 777, 5550 };
		// 进行选择排序
		selectSort(a, a.length);
		// 打印数组
		printArray(a);
	}
}

点赞