自定义的工具类
实现了随机产生数组,打印数组的功能
package com.mao.sort;
import java.util.Random;
/**
* author 小毛桑
*
* @date 2021/10/18 0018 12:26
*/
public class Common {
public int[] setNumber(){
Random random = new Random();
int count = 0;
while (count == 0){
count = random.nextInt(22);
}
int[] arr = new int[count];
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(100);
}
return arr;
}
public void printArray(int[] array){
for (int i = 0; i < array.length; i++) {
System.out.printf(" [" + array[i] +"] ");
}
}
}
排序
冒泡排序
// 冒泡排序
public int[] bubbleSort(int[] array){
int temp = 0;// 临时变量
// 第一次循环遍历之下进行第二次遍历,比较相邻的元素。如果第一个比第二个大,就交换他们两个。一次 i 下,会找到没有排好序的最大的那个元素,将它的位置排好。
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j+1]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
return array;
}
选择排序
// 选择排序
public int[] choiceSort(int[] array){
for (int i = 0; i < array.length -1; i++) {
int min = i,temp;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[min]){
min = j;
}
}
if (i != min){
temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
return array;
}
快速排序
// 快速排序
public int[] quicklySort(int[] array, int low, int high){
int i, j, temp, t;
if(low>high){
return null;
}
i = low;
j = high;
temp = array[low]; // temp 为基准
while (i<j) {
while (temp<=array[j]&&i<j) {//先看右边,依次往左递减
j--;
}
while (temp>=array[i]&&i<j) {//再看左边,依次往右递增
i++;
}
if (i<j) {
t = array[j];
array[j] = array[i];
array[i] = t;
}
}
//最后将基准为与i和j相等位置的数字交换
array[low] = array[i];
array[i] = temp;
quicklySort(array, low, j-1);//递归调用左半数组
quicklySort(array, j+1, high);//递归调用右半数组
return array;
}