1、冒泡排序
比较数组中,两个相邻的元素,如果第一个数比第二个数大,就交换他们的位置 2.每一次比较,都会产生出一个最大,或者最小的数字 3.下一轮则可以少一次排序 4.依次循环,直到结束
//冒泡排序
public void sort(int[] array){
for(int i=1;i<array.length;i++)
for(int j=0;j<array.length-i-1;j++){
if(array[j]>array[j+1]){
int temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
showArray(array);
}
2、选择排序
public static void main(String[] args) {
int[] array = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48};
// 只需要修改成对应的方法名就可以了
selectionSort(array);
System.out.println(Arrays.toString(array));
}
/**
* Description: 选择排序
*
* @param array
* @return void
* @author JourWon
* @date 2019/7/11 23:31
*/
public static void selectionSort(int[] array) {
if (array == null || array.length <= 1) {
return;
}
int length = array.length;
for (int i = 0; i < length - 1; i++) {
// 保存最小数的索引
int minIndex = i;
for (int j = i + 1; j < length; j++) {
// 找到最小的数
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
// 交换元素位置
if (i != minIndex) {
swap(array, minIndex, i);
}
}
}
/**
* Description: 交换元素位置
*
* @param array
* @param a
* @param b
* @return void
* @author JourWon
* @date 2019/7/11 17:57
*/
private static void swap(int[] array, int a, int b) {
int temp = array[a];
array[a] = array[b];
array[b] = temp;
}
3、插入排序
public static void main(String[] args) {
int[] array = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48};
// 只需要修改成对应的方法名就可以了
insertionSort(array);
System.out.println(Arrays.toString(array));
}
/**
* Description: 插入排序
*
* @param array
* @return void
* @author JourWon
* @date 2019/7/11 23:32
*/
public static void insertionSort(int[] array) {
if (array == null || array.length <= 1) {
return;
}
int length = array.length;
// 要插入的数
int insertNum;
for (int i = 1; i < length; i++) {
insertNum = array[i];
// 已经排序好的元素个数
int j = i - 1;
while (j >= 0 && array[j] > insertNum) {
// 从后到前循环,将大于insertNum的数向后移动一格
array[j + 1] = array[j];
j--;
}
// 将需要插入的数放在要插入的位置
array[j + 1] = insertNum;
}
}
4、快速排序
public static void main(String[] args) {
int[] array = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48};
// 只需要修改成对应的方法名就可以了
quickSort(array);
System.out.println(Arrays.toString(array));
}
/**
* Description: 快速排序
*
* @param array
* @return void
* @author JourWon
* @date 2019/7/11 23:39
*/
public static void quickSort(int[] array) {
quickSort(array, 0, array.length - 1);
}
private static void quickSort(int[] array, int left, int right) {
if (array == null || left >= right || array.length <= 1) {
return;
}
int mid = partition(array, left, right);
quickSort(array, left, mid);
quickSort(array, mid + 1, right);
}
private static int partition(int[] array, int left, int right) {
int temp = array[left];
while (right > left) {
// 先判断基准数和后面的数依次比较
while (temp <= array[right] && left < right) {
--right;
}
// 当基准数大于了 arr[left],则填坑
if (left < right) {
array[left] = array[right];
++left;
}
// 现在是 arr[right] 需要填坑了
while (temp >= array[left] && left < right) {
++left;
}
if (left < right) {
array[right] = array[left];
--right;
}
}
array[left] = temp;
return left;
}