整理了一下大学时期的各种排序,很久不用都要忘记了,回忆一下,只是基础版,极端情况下,会有问题
选择排序
public static void selectSort(int[] arr){
for (int i =0;i<arr.length;i++){
int min=arr[i];
int index=i;
for(int j=i+1;j<arr.length;j++){
if(min>arr[j]){
min = arr[j];
index = j;
}
}
if(i!=index){
int temp = arr[i];
arr[i] = min;
arr[index] = temp;
}
}
}
冒泡排序
public static void bubblesort(int[] arr){
int temp = 0;
boolean flag = false;
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]) {
flag = true;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
if (!flag){
break;
}else {
flag = false;
}
}
}
插入排序
public static void insertSort(int[] arr){
for (int i = 1;i<arr.length;i++){
int temp = arr[i];
int index = i-1;
if(arr[i-1]<arr[i]) continue;
for (int t = i-1;t>=0;t--){
if(arr[t]>temp){
index--;
arr[t+1] = arr[t];
}else {
break;
}
}
// for(int j = i-1;j>=index;j--)
// arr[j+1] = arr[j];
arr[index+1]=temp;
}
}
希尔排序
public static void shellSort1(int[] arr){
for (int gap = arr.length/2;gap>0;gap/=2){
for (int i = gap;i<arr.length;i++){
int index=i;
int temp = arr[index];
if (arr[i-gap]<arr[i])
continue;
for (int j = i-gap;j>=0;j-=gap){
if (arr[j]>temp){
index-=gap;
arr[j+gap] = arr[j];
}
}
arr[index] = temp;
}
}
}
归并排序
public static void mergeSort(int[] arr,int left,int right,int[] temp){
if (left<right){
int mid = (left+right)/2;
mergeSort(arr,left,mid,temp);
mergeSort(arr,mid+1,right,temp);
merge(arr,left,mid,right,temp);
}
}
public static void merge(int[] arr,int left,int mid,int right,int[] temp){
int i = left;
int j = mid+1;
int t = 0;
while (i<=mid&&j<=right){
if (arr[i]<=arr[j]) {
temp[t] = arr[i];
t++;
i++;
}else {
temp[t] = arr[j];
t++;
j++;
}
}
while (i<=mid){
temp[t]=arr[i];
t++;
i++;
}
while (j<=right){
temp[t] = arr[j];
t++;
j++;
}
t=0;
int templeft = left;
while (templeft<=right){
arr[templeft]=temp[t];
templeft++;
t++;
}
}
快排
public static void quickSort(int[] arr,int left,int right){
int l = left;
int r = right;
int pivot = arr[(left+right)/2];
int temp=0;
while (l<r){
while (arr[l]<pivot){
l+=1;
}
while (arr[r]>pivot){
r-=1;
}
if(l>=r){
break;
}
temp=arr[l];
arr[l] = arr[r];
arr[r] = temp;
if(arr[l]==pivot)
r-=1;
if(arr[r]==pivot)
l+=1;
}
if (l==r){
l++;
r--;
}
if (left<r){
quickSort(arr,left,r);
}
if (right>l){
quickSort(arr,l,right);
}
}
基数排序
public static void radixSort(int[] arr){
int max = arr[0];
for (int i = 1;i < arr.length;i++){
if (arr[i]>max)
max=arr[i];
}
int maxLength = (max+"").length();
int[][] bucket = new int[10][arr.length];
int[] bucktElementCounts = new int[10];
for (int i = 0,n=1;i < maxLength;i++,n*=10){
for (int j = 0;j < arr.length;j++){
int digitOfElement = arr[j] / n % 10;
bucket[digitOfElement][bucktElementCounts[digitOfElement]] = arr[j];
bucktElementCounts[digitOfElement]++;
}
int index = 0;
for (int k = 0;k < bucktElementCounts.length;k++){
if (bucktElementCounts[k]!=0){
for (int l = 0;l<bucktElementCounts[k];l++){
arr[index++] = bucket[k][l];
}
}
bucktElementCounts[k] = 0;
}
}
}