1、给一个数组{9,4,7,2,0,1,-1,5,-6},长度为n
2、共进行n-1次遍历
3、第一次遍历时,先从n个数据中取出最小的数据,和index = 0的数据进行交换。
3、第二次遍历时,先从n-1个数据中取出最小的数据,和index = 1的数据进行交换。
4、重复以上步骤,直到进行第n-1次遍历
O(n^2) ;内排序;不稳定;8万条数据约3秒
package Sort;
import java.util.Arrays;
public class SelectSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {9,4,7,2,0,1,-1,5,-6};
SelectSort selectSort = new SelectSort();
selectSort.selectSort(arr);
System.out.println(Arrays.toString(arr));
}
简单选择排序,
// 思路:遍历n-1次,第x次遍历时,从index=x-1到n-1中选择最小的数据,放在x-1的位置。
public void SelectSort(int[] arr) {
if(arr.length == 0) {
return;
}
int minIndex;
int temp;
for(int i = 0; i < arr.length - 1; i++) {//遍历n-1次
minIndex = i;
for(int j = i + 1; j < arr.length; j++) {
if(arr[minIndex] > arr[j]) {//不是相邻的比较,是剩下的和minIndex比较
minIndex = j;
}
}
if(minIndex != i) {
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
}
package Sort;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class SelectSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
// int[] arr = {9,4,7,2,0,1,-1,5,-6};
int[] arr = new int[80000];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int)(Math.random()*8000000);
}
Date date1 = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date1String = simpleDateFormat.format(date1);
System.out.println("前:"+date1String);
SelectSort selectSort = new SelectSort();
selectSort.selectSort(arr);
Date date2 = new Date();
String date2String = simpleDateFormat.format(date2);
System.out.println("后:"+date2String);
}
简单选择排序,
// 思路:遍历n-1次,第x次遍历时,从index=x-1到n-1中选择最小的数据,放在x-1的位置。
public void SelectSort(int[] arr) {
if(arr.length == 0) {
return;
}
int minIndex;
int temp;
for(int i = 0; i < arr.length - 1; i++) {//遍历n-1次
minIndex = i;
for(int j = i + 1; j < arr.length; j++) {
if(arr[minIndex] > arr[j]) {//不是相邻的比较,是剩下的和minIndex比较
minIndex = j;
}
}
if(minIndex != i) {
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
}