java的简单排序、冒泡排序、插入排序、归并排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33243189/article/details/80363602

    简单排序:按顺序拿值都跟其他值对比,小于则交换位置。

    private static void simpleLookUp(int[] a) {
int length = a.length;
int temp  = a[0];
for(int i = 0 ;i <length ; i++){
for(int j = i + 1 ;j <length ; j++){
if(a[i] > a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
for(int k = 0 ;k <a.length ; k++){
System.out.print(a[i]);
}
}
}

}

    冒泡排序:两个数两两对比,如果大于这个数就交换位置。

    private static void maopaoLookUp(int[] a) {
int length = a.length - 1;
int temp  = a[0];
for(int i = 0 ;i <length ; i++){
for(int j = 0 ;j <length - i ; j++){
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}

}

    插入排序:把无序的数据插入有序的序列,当前的的数据(i)插入{0~i-1}序列中 

    private static void insertLookUp(int[] a){

for(int i = 1;i<a.length;i++){

for(int j=0 ; j<= i-1 ; j++){
if(a[i] > a[j]){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}

}

    归并排序:假设两个有序的序列a[0~i]、b[0~j]进行合并排序到全新的序列c[0~i+j]。 a[i]与b[j]对比,若a[i]小则c[k]=a[i],然 后a[i+1]与b[j]比对;a[i]与b[j]对比,若b[j]小则c[k]=b[j],然后a[i]与b[j+1]比对。

    //数组分割
private static void division(int[] a,int low,int high){
int mid = (low+high) / 2;
if(low<high){
//左归并
division(a,low,mid);
//右归并
division(a,mid+1,high);
//左右归并
mergeLookUp(a, low, mid, high);
}

}


    //参数:数组a[low,high],左数组 a[low,mid],右数组a[mid+1,high]
//最后把排序好的temp[] 复制到a[low,high]
private static void mergeLookUp(int[] a,int low,int mid,int high){
int n = high - low + 1;
int[] p = new int[n];
int i = low;
int j = mid+1;
for(int k = 0;k<n;k++){
if(i>mid){
p[k]=a[j];
j++;
continue;
}
if(j>high){
p[k]=a[i];
i++;
continue;
}
if(a[i]<=a[j]){
p[k] = a[i];
i++;
continue;
}
if(a[i]>a[j]){
p[k] = a[j];
j++;
continue;
}
}

猜你喜欢

转载自blog.csdn.net/qq_33243189/article/details/80363602