package com.guigu.sort;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
/**
* @author: guorui fu
* @versiion: 1.0
* 选择排序
* 1.假定当前数为最小数,和后面的数比较,如果发现有更小数,
* 则重新确定最小数,并得到下标 遍历到数组最后,得到本轮最小数和下标
* 2.交换
* 时间复杂度是O(n^2)
*/
public class SelectSort {
public static void main(String[] args) {
// int[] arr = {3, 9, -1, 10, -2,12,53};
int[] arr = new int[80000];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int)(Math.random()*80000);
}
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("起始时间=" + simpleDateFormat.format(date));
// Arrays.sort(arr);//自带排序更快
int minIndex ;
int min ;
for (int i = 0; i < arr.length - 1; i++) {
minIndex = i;
min = arr[i];
for (int j = i + 1 ; j < arr.length; j++) {
if (arr[minIndex] > arr[j]){
min = arr[j];
minIndex = j;
}
}
if (minIndex != i){
arr[minIndex] = arr[i];
arr[i] = min;
}
}
Date date1 = new Date();
System.out.println("结束时间=" + simpleDateFormat.format(date1));
System.out.print(Arrays.toString(arr));
}
}
[算法] 选择排序
最新推荐文章于 2024-06-12 10:00:23 发布