排序方法
代码
package com.qf;/*
* zt
* 2020/7/23
* 15:44
*
*/
import sun.plugin2.message.SetAppletSizeMessage;
public class Demo2 {
public static void main(String[] args) {
int[] nums = {50,20,30,51,48};
for (int num : nums) {
System.out.print(num+",");
}
shellSort(nums);
System.out.println();
for (int num : nums) {
System.out.print(num+",");
}
}
//冒泡排序 :n个数字来排列,两两比较,小靠前,外层循环n-1,内层循环n-1-i
public static void bubbleSort(int[] arr){
for (int i = 0; i < arr.length-1; i++) {
for (int j = 0; j < arr.length-i-1; j++) {
if(arr[j]>arr[j+1]){
int t = arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
}
//选择
public static void getxuanze(int[] arr){
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if(arr[i] > arr[j]){
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
}
//插入
public static void inserSort(int[] arr){
for (int i = 1; i < arr.length; i++) {
for (int j = i - 1; j >= 0; j--) {
if(arr[j] > arr[j + 1]){
int t = arr[j];
arr[j] = arr[j+1];
arr[j + 1] = t;
}
}
}
}
//优化插入排序
public static void inserSort2(int[] arr){
for (int i = 1; i < arr.length; i++) {
int t = arr[i];
int pos = i-1;
while(pos>=0 && arr[pos] > t){
arr[pos + 1] = arr[pos];
pos--;
}
arr[pos+1]=t;
}
}
//希尔排序
public static void shellSort(int[] arr){
int gap = arr.length;
while (true){
gap /= 2;
for (int i = 0; i < gap; i++) {
for (int j = i + gap; j < arr.length; j+=gap) {
int t = arr[j];
int pos = j-gap;
while(pos >= 0 && arr[pos] > t){
arr[pos + gap] = arr[pos];
pos -= gap;
}
arr[pos + gap] = t;
}
}
if(gap == 1){
break;
}
}
}
}