Selection Sort
- 算法思维:从
0到n-1每次取一个为i, 和i后面的元素进行比较 - 令
int k = i;如果发现比i位置上的还小,则将该位置的角标赋值给k。 - 最后交换i 和 k的位置;每一趟都能排好一个最小的值。
package simpleAlgorithm;
/**
* @Author: WhaleFall541
* @Date: 2021/4/4 16:08
* 算法思维:从`0`到`n-1`每次取一个为`i`, 和i后面的元素进行比较
* 令`int k = i;`如果发现比`i`位置上的还小,则将该位置的角标赋值给k。
* 最后交换i 和 k的位置;每一趟都能排好一个最小的值。
*/
public class SelectSort {
public static void main(String[] args) {
int[] arr = {-1111, 20, -3, -10, 100, -255};
selectSort(arr);
StringBuilder sb = new StringBuilder();
for (int i : arr)
sb.append(i).append(" ");
System.out.println("sb = " + sb);
}
//选择排序
private static void selectSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int k = i;// i是要排序的数下标
// 跟i下标后面的每个元素比较记录下来arr[k]最小的k值
for (int j = i + 1; j < arr.length; j++) {
if (arr[k] > arr[j])
k = j;
}
// 最小的arr[k] 和 当前排序位置arr[i]互换
swap(arr, i, k);
}
}
private static void swap(int[] arr, int a, int b) {
int tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
}
Agreement
The code part of this work is licensed under Apache License 2.0 . You may freely modify and redistribute the code, and use it for commercial purposes, provided that you comply with the license. However, you are required to:
- Attribution: Retain the original author's signature and code source information in the original and derivative code.
- Preserve License: Retain the Apache 2.0 license file in the original and derivative code.
- Attribution: Give appropriate credit, provide a link to the license, and indicate if changes were made.
- NonCommercial: You may not use the material for commercial purposes. For commercial use, please contact the author.
- ShareAlike: If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.