java常见的排序

冒泡排序:遍历数组中的每个元素,一次比较两个元素,大的往后移动

public static void gulugulu(int[] num) {
		int temp;
		int len=num.length;
		for(int i=0;i<len-1;i++) {
			for(int j=0;j<len-i-1;j++) {
				if (num[j+1]<num[j]) {
					temp=num[j+1];
					num[j+1]=num[j];
					num[j]=temp;
				}
			}
		}
		
	}

   

快速排序:使用分治策略,通过一个基准将他们分成两个部分,左边比他小,右边比他大。getMiddle就是用来确定这个基准的

public static int getMiddle(int[] numbers,int low,int high) {
		int temp=numbers[low];
		while(low<high) {
			while(low<high&&temp<numbers[high]) {
				high--;
			}
			numbers[low]=numbers[high];
			while(low<high&&temp>numbers[low]) {
				low++;
			}
			numbers[high]=numbers[low];
		}
		numbers[low]=temp;
		return low;//返回中轴节点
	}
	public static void quickSort(int[] numbers,int low,int high) {
		if (low<high) {
			int middle=getMiddle(numbers, low, high);
			quickSort(numbers, low, middle-1);//左边小的
			quickSort(numbers, middle+1, high);
		}
	}

选择排序:遍历找到最小的加入进去,然后次小的

public static void selectSort(int[] num) {
		
		int t;
		for(int i=0;i<num.length;i++) {
			int index=i;
			for(int j=i+1;j<num.length;j++) {
				
				if (num[index]>num[j]) {
					index=j;
				}
			}
			if (index!=i) {
				t=num[i];
				num[i]=num[index];
				num[index]=t;
			}
		}
		
	}

插入排序:从头开始,前面都是排好序的,找到一个元素的合适位置,数组整体移动,插入进去

public static void charu(int[] array) {
		int temp;
		for(int i=1;i<array.length;i++) {
			temp=array[i];
			while(i>=1&&array[i-1]>temp) {
				array[i]=array[i-1];
				i--;
			}
			array[i]=temp;
		}
	}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值