Java数据结构之八大排序算法
冒泡排序
public static void bubbleSort(int[] arr) {
int flag=0;
for(int i=0;i<arr.length-1;i++)
for(int j=0;j<arr.length-1-i;j++){
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = 1;
}
if(flag == 0) break;
}
}
快速排序
public static void quickSort(int[] arr, int start, int end) {
if(start >= end){
return;
}
int stand = arr[start]; // 标准数
int low = start; // 低位
int high = end; // 高位
while(low<high){
while(low<high && stand<=arr[high]){
high--;
}
arr[low] = arr[high];
while(low<high && stand>=arr[low]){
low++;
}
arr[high]=arr[low];
}
arr[low]=stand;
// 递归调用
quickSort(arr, start, low);
quickSort(arr, low+1, end);
插入排序
public static void insertSort(int[] arr){
for(int i=1;i<arr.length;i++){
if(arr[i]<arr[i-1]){
int temp = arr[i];
int j;
for(j=i-1;j>=0&&arr[j]>temp;j--){
arr[j+1] = arr[j];
}
arr[j+1]=temp;
}
}
}
希尔排序
public static void shellSort(int[] arr){
int d=arr.length/2;
int x,j,k=1;
while(d>=1) {
for(int i=d;i<arr.length;i++) {
x=arr[i];
j=i-d;
//直接插入排序,会向前找所适合的位置
while(j>=0 && arr[j]>x) {
//交换位置
arr[j+d]=arr[j];
j=j-d;
}
arr[j+d]=x;
}
d=d/2;
System.out.println("第"+ k++ +"趟:"+Arrays.toString(arr));
}
}
选择排序
public static void selectSort(int[] arr){
for(int i=0;i<arr.length;i++){
int minIndex = i;
for(int j=i+1;j<arr.length;j++){
if(arr[minIndex]>arr[j]){
minIndex = j;
}
}
if(minIndex != i){
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}