java 排序基础

1、选择排序:

思路:选择排序(降序)每一轮循环都找到剩余数中最大的数放在当前轮数的首位,即选出最大值;

如第一轮 i = 0 时:该轮首位为 nums[0] ,然后从nums[1] 开始比较,每找到比nums[0] 大的数即交换数据,直到这轮结束。下一轮以nums[1] 为首位,从nums[2] 开始,直到结束。

升序排序反之即可。

 
选择排序{3,2,4,1}(降序)
i      j123
0{3,2,4,1}{4,2,3,1}                      
1{4,3,2,1}            
2
3

package com.planz;

public class SelectSort {
	public static void main(String[] args){
		int[] nums1 = orderBy(new int[]{3,2,4,1}, "desc");
		for (int i = 0; i < nums1.length; i++) {
			System.out.print(nums1[i]+" ");
		}
		System.out.println();
		int[] nums2 = orderBy(new int[]{3,2,4,1}, "esc");
		for (int i = 0; i < nums2.length; i++) {
			System.out.print(nums2[i]+" ");
		}
	}
	public static int[] orderBy(int[] nums,String type){
		if (type.equalsIgnoreCase("desc")) {
			for (int i = 0; i < nums.length; i++) {
				for (int j = i+1; j < nums.length; j++) {
					if (nums[i]<nums[j]) {
						int tem = nums[i];
						nums[i] = nums[j];
						nums[j] = tem;
					}
				}
			}
		}else if(type.equalsIgnoreCase("esc")){
			for (int i = 0; i < nums.length; i++) {
				for (int j = i+1; j < nums.length; j++) {
					if (nums[i]>nums[j]) {
						int tem = nums[i];
						nums[i] = nums[j];
						nums[j] = tem;
					}
				}
			}
		}
		
		return nums;
	}
}
2、冒泡排序:

思路:(1)冒泡排序分两个数据域,一个无序区,每次需要遍历比较,每轮递减,一个有序区,每轮递增,在数组末尾;

(2)冒泡排序默认为升序排序,小的数像气泡一样上浮(左移),大的数像石头一样下沉(右移);

(3)外层循环轮数为n-1 ,内层遍历个数为无序区;

冒泡排序{3,2,4,1}(升序)
i      j012
0{2,3,4,1}{2,3,4,1}{2,3,1,4}
1{2,3,1,4}{2,1,3,4}
2{1,2,3,4} 

package com.planz;

public class BubbleSort {
	public static void main(String[] args){
		int[] nums = orderBy(new int[]{3,2,4,1});
		for (int i = 0; i < nums.length; i++) {
			System.out.print(nums[i]+" ");
		}
	}
	public static int[] orderBy(int[] nums){
		for (int i = 0; i < nums.length-1; i++) {//循环论数(n-1)次循环即可
			for (int j = 0; j < nums.length-1-i; j++) {//无序区的遍历,剩余的为已排好的有序区
				if (nums[j]>nums[j+1]) {//小的数上浮
					int tem = nums[j];
					nums[j] = nums[j+1];
					nums[j+1] = tem;
				}
				
			}
			
		}
		return nums;
	}
}

此外还有快速排序、直接插入排序、二分法、使用Array.sort(int[] array)等等,在此暂时不赘述了,嘻嘻....

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值