java 排序

冒泡排序(两两比较,交换顺序)

	//冒泡排序(两两比较,换位)
	public static int[] bubble(int[] arr){
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr.length-i-1; j++) {
				if(arr[j]<=arr[j+1]){
					int temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
		return arr;
		
	}

//选择排序(找出最大,放到已经排好的序列后面)

	public static int[] selection(int[] arr){
		
		for (int i = 0; i < arr.length; i++) {
			int temp =arr[i];
			int temp1 = i;
			for (int j = i; j < arr.length-1; j++) {
				temp = arr[j+1]>temp ? arr[j+1]:temp;	
			}
			for (int j = i; j < arr.length; j++) {
				if(temp==arr[j]){
					temp1=j;
				}
			}
			int temp3 = arr[i];
			arr[i] = arr[temp1];
			arr[temp1] = temp3;
		}
		return arr;
		
	}
	@Test//选择排序
	public void selectSort(){
		int[] c = {23,12,34,56,4,7,13};
		//假定待排序数组的第一个元素为最小值,将它与其后的每一个元素进行比较,最终确定在这个待排序数组中最小值元素的位置,最后判断最小值元素是否为第一个元素,
		//如果不是,交换 
		for(int i=0;i<c.length-1;i++){
			int temp ;
			int minIndex = i;//假定第一个元素是最小值
			for(int j=i+1;j<c.length;j++){
				if(c[minIndex]>c[j]){
					minIndex = j;
				}
			}
			if(minIndex!=i){
				temp = c[minIndex];
				c[minIndex] = c[i];
				c[i] = temp;
			}
		}
		for (int i : c) {
			System.out.println(i);
		}
		
	}

插入排序(依次插入前面的序列)

	public static int[] insert(int[] arr){
		for (int i = 0; i < arr.length-1; i++) {
			for (int j = 0; j < i+1; j++) {
				if(arr[i+1]>arr[j]){
					int temp = arr[i+1];
					for (int k = i+1; k > j; k--) {
						arr[k]=arr[k-1];
					}
					arr[j] =temp;	
					break;
				}	
			}
		}
		return arr;
	}

	//插入排序
	@Test
	public void insertSort(){
		int[] c = {23,12,34,56,4,7,13};
		//12,23,34
		for(int i=1;i<c.length;i++){//自第二位起,一次取一个待排序的元素
			int temp=c[i];
			int j=i-1;
			while(j>=0&&temp<c[j]){
				c[j+1]=c[j];
				j=j-1;
			}
			c[j+1]=temp;
		}
		
		for (int i : c) {
			System.out.println(i);
		}
	}


	@Test//插入排序
		public void insertSort1(){
			int[] c = {23,12,34,56,4,7,13};
			//12,23,34
			for(int i=1;i<c.length;i++){//自第二位起,一次取一个待排序的元素
				int temp=c[i];
				int j=0;
				for(j=i-1;j>=0&&c[j]>temp;j--){//将i之前的每一个比temp要大的元素都后一移一位
					c[j+1]=c[j];
				}
				c[j+1]=temp;
			}
			
			for (int i : c) {
				System.out.println(i);
			}
		}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值