四个排序
冒泡排序
import java.util.Arrays;
public class Maopao{
public static void main(String[] args){
int[] arr={55,33,44,22,11};
bubbleSort(arr);
System.out.println(Arrays.toString(arr))
}
public static void bubbleSort(int[] arr){
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr.length-1;j++){
if(arr[j]>arr[j+1]){
arr[j]=arr[j]^arr[j+1];
arr[j+1]=arr[j]^arr[j+1];
arr[j]=arr[j]^arr[j+1];
}
}
}
}
}
选择排序
import java.util.Arrays;
public class Choose {
public static void main(String[] args) {
int[] arr={55,33,44,11,22};
selectSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void selectSort(int[] arr){
for (int i = 0; i <arr.length ; i++) {
int minIndex=i;
int min=arr[i];
for (int j = i+1; j <arr.length ; j++) {
if (arr[j]<arr[minIndex]){
minIndex=j;
}
}
arr[i]=arr[minIndex];
arr[minIndex]=min;
}
}
}
插入排序
import java.util.Arrays;
public class Charu {
public static void main(String[] args) {
int[] arr={55,33,44,11,22};
insertSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void insertSort(int[] arr){
for (int i = 0; i < arr.length ; i++) {
int current=arr[i];
int prevIndex=i-1;
while (prevIndex>=0 && current<arr[prevIndex]){
arr[prevIndex+1]=arr[prevIndex];
prevIndex--;
}
arr[prevIndex+1]=current;
}
}
}
快速排序
import java.util.Arrays;
public class Quickly {
public static void main(String[] args) {
int[] arr={55,33,44,11,22};
quicklySort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
public static void quicklySort(int[] arr,int left,int right){
if (left>=right){
return;
}
int jizhun=arr[left];
int i=left;
int j=right;
while (i!=j){
while (j>i && arr[j]>jizhun){
j--;
}
while ((j>i && arr[i]<jizhun)){
i++;
}
if (i<j){
arr[i]=arr[i]^arr[j];
arr[j]=arr[i]^arr[j];
arr[i]=arr[i]^arr[j];
}
}
if (arr[i]<jizhun){
arr[left]=arr[i];
arr[i]=jizhun;
}
quicklySort(arr,0,i-1);
quicklySort(arr,i+1,right);
}
}