www. On IT Road .com

选择排序 Java 实现示例

下面是 java 中选择排序实现 的示例。

public class SelectionSortExample 
{
	public static void main(String[] args) {
		// 要排序的数组
		Integer[] array = new Integer[] { 12, 13, 24, 10, 3, 6, 90, 70 };
		// 执行选择排序
		selectionSort(array, 0, array.length);
		// 查看排序后的数组
		System.out.println(Arrays.toString(array));
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void selectionSort(Object[] array, int fromIndex, int toIndex) 
	{
		Object d;
		for (int currentIndex = fromIndex; currentIndex < toIndex; currentIndex++) 
		{
			int indexToMove = currentIndex;
			for (int tempIndexInLoop = currentIndex + 1; tempIndexInLoop < toIndex; tempIndexInLoop++) 
			{
				if (((Comparable) array[indexToMove]).compareTo(array[tempIndexInLoop]) > 0) 
				{
					//Swapping
					indexToMove = tempIndexInLoop;
				}
			}
			d = array[currentIndex];
			array[currentIndex] = array[indexToMove];
			array[indexToMove] = d;
		}
	}
}

输出:

[3, 6, 10, 12, 13, 24, 70, 90]
使用Java实现选择排序

选择排序反复从未排序的部分中选择最低或者最高的元素,并将其移动到已排序部分的末尾。
大多数情况下,性能方面,它甚至比插入排序还要慢。

日期:2020-09-17 00:09:32 来源:oir作者:oir