栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java实现排序【归并排序、归并排序、直接选择排序、冒泡排序】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java实现排序【归并排序、归并排序、直接选择排序、冒泡排序】

归并排序:
public void sort(int[] nums,int left,int right,int[] temp){
	if(left < right){
		int mid = left + (right - left) / 2;//开始递归划分

		sort(nums,left,mid,temp);//归并排序左部分(left,mid)

		sort(nums,mid+1,right,temp);//归并排序右部分(mid+1,right)

		merge(nums,left,mid,right,temp);//合并
	}
}

private void merge(int[] nums, int left, int mid, int right, int[] temp) {
	int i = left;      // 左部分首元素
	int j = mid + 1;   // 右部分首元素
	int t = 0;

	while(i <=mid && j <=right){//在范围之内
		if(nums[i] <= nums[j]){
			temp[t++] = nums[i++];
		}else{
			temp[t++] = nums[j++];
	}
}

	while (i <= mid){//右边遍历完事了   左边还剩呢
		temp[t++] = nums[i++];
	}
	while(j <= right){//左边遍历完事了   右边还剩了
		temp[t++] = nums[j++];
	}
	
	t = 0;//将temp中的元素  全部都copy到原数组里边去
	while (left <=right){
		nums[left++] = temp[t++];
	}
}

快速排序:
public void QKSort(int a[], int low, int high){
        if(low < high){
            int pos = QKPass(a, low, high);
            QKSort(a, low, pos-1);
            QKSort(a, pos+1, high);
        }
    }

public int QKPass(int a[], int low, int high){
    int x = a[low];

    while (low < high){
        while(low < high && a[high] >= x){
            high--;
        }
        if(low < high){
            a[low] = a[high];
            low++;
        }
        while(low < high && a[low] <= x){
            low++;
        }
        if(low < high){
            a[high] = a[low];
            high--;
        }
    }
    a[low] = x;
    return low;
}
选择排序:
public static int[] ChoiceSort(int[] a){
    if(a == null || a.length <= 0){
        return null;
    }
    for (int i = 0; i < a.length-1; i++) {
        int min = i;
        for(int j = i;j < a.length;j++){
            if(a[min] > a[j])
                min = j;
        }
        if(i != min){
            int temp = a[min];
            a[min] = a[i];
            a[i] = temp;
        }
    }
    return a;
}
冒泡排序:
//冒泡排序
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;
		}
		
	}
	
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/867247.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号