import java.util.Random;
/**
* @author NOknow
* @version 1.0
* @CreateDate 2019/10/12
* @Desc
*/
public class SoutFunction {
public static void main(String[] args) {
int[] dataSrc = getRandomIntArray(10, 100);
print("dataSrc ", dataSrc);
bubbleSort(dataSrc);
print("bubbleSort ", dataSrc);
selectionSort(dataSrc);
print("selectionSort", dataSrc);
insertionSort(dataSrc);
print("insertionSort", dataSrc);
}
private static int[] getRandomIntArray(int count, int maxNum) {
int[] nums = new int[count];
Random random = new Random();
random.setSeed(System.currentTimeMillis());
int i = 0;
while (i < count) {
nums[i++] = random.nextInt(maxNum + 1);
}
return nums;
}
/**
* 插入排序法
*
* @param dataSrc 要进行排序整型数据源
*/
private static void insertionSort(int[] dataSrc) {
for (int i = 1; i < dataSrc.length; i++) {
for (int j = i; j > 0; j--) {
if (dataSrc[j] < dataSrc[j - 1]) {
int temp = dataSrc[j - 1];
dataSrc[j - 1] = dataSrc[j];
dataSrc[j] = temp;
}
}
}
}
/**
* 选择排序法
*
* @param dataSrc 要进行排序整型数据源
*/
public static void selectionSort(int[] dataSrc) {
for (int i = 0; i < dataSrc.length; i++) {
int minIndex = i;
for (int j = i + 1; j < dataSrc.length; j++) {
if (dataSrc[minIndex] > dataSrc[j]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = dataSrc[minIndex];
dataSrc[minIndex] = dataSrc[i];
dataSrc[i] = temp;
}
}
}
/**
* 冒泡排序法(升序)
*
* @param dataSrc 要进行排序整型数据源
*/
public static void bubbleSort(int[] dataSrc) {
for (int i = 0; i < dataSrc.length; i++) {
for (int j = i + 1; j < dataSrc.length; j++) {
if (dataSrc[i] > dataSrc[j]) {//这里换成小于号就是降序排序
int temp = dataSrc[i];
dataSrc[i] = dataSrc[j];
dataSrc[j] = temp;
}
}
}
}
private static void print(String tip, int[] data) {
System.out.print(tip + " : ");
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + "\t");
}
System.out.println();
}
}