使用 Java 的 DSA - 选择排序
概述
选择排序是一种简单的排序算法。此排序算法是一种基于就地比较的算法,其中列表分为两部分,左端的排序部分和右端的未排序部分。最初排序部分为空,未排序部分为整个列表。
从未排序数组中选择最小元素并与最左边的元素交换,该元素成为排序数组的一部分。此过程继续将未排序数组边界向右移动一个元素。
此算法不适用于大型数据集,因为其平均和最坏情况复杂度为 O(n2),其中 n 为项目数。
伪代码
Selection Sort ( A: array of item)
procedure selectionSort( A : array of items )
int indexMin
for i = 1 to length(A) - 1 inclusive do:
/* 将当前元素设置为最小值*/
indexMin = i
/* 检查元素是否最小 */
for j = i+1 to length(A) - 1 inclusive do:
if(intArray[j] < intArray[indexMin]){
indexMin = j;
}
end for
/* 将最小元素与当前元素交换*/
if(indexMin != i) then
swap(A[indexMin],A[i])
end if
end for
end procedure
演示程序
package com.tutorialspoint.simplesort;
import java.util.Arrays;
public class SelectionSortDemo {
public static void main(String[] args){
int[] sourceArray = {4,6,3,2,1,9,7};
System.out.println("Input Array: "
+ Arrays.toString(sourceArray));
printline(50);
System.out.println("Output Array: "
+ Arrays.toString(selectionSort(sourceArray)));
printline(50);
}
public static void printline(int count){
for(int i=0;i <count-1;i++){
System.out.print("=");
}
System.out.println("=");
}
public static int[] selectionSort(int[] intArray){
int indexMin;
// 循环遍历所有数字
for(int i=0; i < intArray.length-1; i++){
// 将当前元素设置为最小值
indexMin = i;
// 检查元素是否最小
for(int j=i+1;j<intArray.length;j++){
if(intArray[j] < intArray[indexMin]){
indexMin = j;
}
}
if(indexMin != i){
System.out.println(" Items swapped: [ "
+ intArray[i] + ", " + intArray[indexMin] +" ]" );
// 交换数字
int temp=intArray[indexMin];
intArray[indexMin] = intArray[i];
intArray[i] = temp;
}
System.out.println("iteration "+(i+1) +"#: "
+ Arrays.toString(intArray));
}
return intArray;
}
}
如果我们编译并运行上述程序,则会产生以下结果 −
Input Array: [4, 6, 3, 2, 1, 9, 7]
==================================================
Items swapped: [ 4, 1 ]
iteration 1#: [1, 6, 3, 2, 4, 9, 7]
Items swapped: [ 6, 2 ]
iteration 2#: [1, 2, 3, 6, 4, 9, 7]
iteration 3#: [1, 2, 3, 6, 4, 9, 7]
Items swapped: [ 6, 4 ]
iteration 4#: [1, 2, 3, 4, 6, 9, 7]
iteration 5#: [1, 2, 3, 4, 6, 9, 7]
Items swapped: [ 9, 7 ]
iteration 6#: [1, 2, 3, 4, 6, 7, 9]
Output Array: [1, 2, 3, 4, 6, 7, 9]
==================================================

