Java 数据结构 - 选择排序
选择排序是一种简单的排序算法。这种排序算法是一种原地比较排序算法,其中列表被分成两个部分,排序部分在左侧,未排序部分在右侧。最初,排序部分为空,未排序部分是整个列表。
从未排序数组中选择最小的元素,并将其与最左边的元素交换,该元素成为排序数组的一部分。此过程继续将未排序数组边界向右移动一个元素。
此算法不适用于大型数据集,因为其平均和最坏情况复杂度为 Ο(n2),其中 n 是项目的数量。
算法
Step 1: Set MIN to location 0 in the array. Step 2: Search the minimum element in the list. Step 3: Swap with value at location MIN. Step 4: Increment MIN to point to next element. Step 5: Repeat until list is sorted.
示例
import java.util.Arrays;
public class SelectionSort {
public static void main(String args[]) {
int myArray[] = {10, 20, 25, 63, 96, 57};
int n = myArray.length;
System.out.println("Contents of the array before sorting : ");
System.out.println(Arrays.toString(myArray));
for (int i=0 ;i< n-1; i++) {
int min = i;
for (int j = i+1; j<n; j++) {
if (myArray[j] < myArray[min]) {
min = j;
}
}
int temp = myArray[min];
myArray[min] = myArray[i];
myArray[i] = temp;
}
System.out.println("Contents of the array after sorting : ");
System.out.println(Arrays.toString(myArray));
}
}
输出
Contents of the array before sorting : [10, 20, 25, 63, 96, 57] Contents of the array after sorting : [10, 20, 25, 57, 63, 96]
广告