java7种排序算法
1.冒泡排序
public void bubbleSort(int[] array){
for (int i = 0; i < array.length-1; i++) {
boolean flag=false;
for (int j = i; j <array.length-1-i ; j++) {
if (array[j]>array[j+1]){
int temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
flag=true;
}
}
if (!flag){
return;
}
}
}
2.插入排序
public void insertSort(int[] array){
int insertValue=0;
int index=0;
for (int i = 1; i < array.length; i++) {
insertValue=array[i];
index=i-1;
while (index >=0&&insertValue<array[index]){
array[index+1]=array[index];
index--;
}
if (index+1!=i){
array[index+1]=insertValue;
}
}
}
3.选择排序
public void selectSort(int[] array){
for (int i = 0; i <array.length-1 ; i++) {
int min=array[i];
int index=i;
for (int j = i+1; j < array.length; j++) {
if (array[j]<min){
index=j;
min=array[j];
}
}
if (index!=i){
array[index]=array[i];
array[i]=min;
}
}
}
4.希尔排序
public void shellSort(int[] array){
for (int gap = array.length/2; gap > 0; gap/=2) {
int insertValue=0;
int index=0;
for (int i = gap; i < array.length; i++) {
insertValue=array[i];
index=i-gap;
while (index>=0&&insertValue<array[index]){
array[index+gap]=array[index];
index-=gap;
}
if (index!=i-gap){
array[index+gap]=insertValue;
}
}
}
}
5.归并排序
public void merge(int[] array,int left,int mid,int right,int[] temp){
int l=left;
int r=mid+1;
int t=0;
while (l<=mid&&r<=right){
if (array[l]<array[r]){
temp[t]=array[l];
l++;
}else {
temp[t]=array[r];
r++;
}
t++;
}
while (l<=mid){
temp[t]=array[l];
t++;
l++;
}
while (r<=right){
temp[t]=array[r];
r++;
t++;
}
t=0;
int tempLeft=left;
while (tempLeft<=right){
array[tempLeft]=temp[t];
tempLeft++;
t++;
}
}
public void divide(int[] array,int left,int right,int[] temp){
if (left<right) {
int mid = (left + right) / 2;
divide(array, left, mid, temp);
divide(array, mid + 1, right, temp);
merge(array, left, mid, right, temp);
}
}
6.快速排序
public void quickSort(int[] array,int left,int right){
if (left<right){
int l=left;
int r=right;
int x=array[right];
while (l<r){
while (l<r&&array[l]<=x){
l++;
}
if (l<r&&array[l]>x){
array[r]=array[l];
r--;
}
while (l<r&&array[r]>=x){
r--;
}
if (l<r&&array[r]<x){
array[l]=array[r];
l++;
}
}
array[l]=x;
quickSort(array,left,l-1);
quickSort(array,l+1,right);
}
}
7.基数排序(基于桶排序)
public void radixSort(int[] array){
int max=array[0];
for (int j : array) {
if (j > max) {
max = j;
}
}
int maxLength=(max+"").length();
int[][] bucket=new int[10][array.length];
int[] bucketElementCounts=new int[10];
for (int i = 0,n=1; i < maxLength; i++,n*=10) {
for (int element : array) {
int digitOfElement=element/n%10;
bucket[digitOfElement][bucketElementCounts[digitOfElement]]=element;
bucketElementCounts[digitOfElement]++;
}
int index=0;
for (int j = 0; j < 10; j++) {
if (bucketElementCounts[j]!=0){
for (int k = 0; k < bucketElementCounts[j]; k++) {
array[index++]=bucket[j][k];
}
}
bucketElementCounts[j]=0;
}
}
}