调整顺序,使奇数在前,偶数在后

版权声明:be the one ~you will be the one~~ https://blog.csdn.net/Hqxcsdn/article/details/88037819

在这里插入图片描述
本题有一种快速排序的感觉,和快速排序不同的是,快速排序 要自己定义一个 标记值 ,最后还有进行 左右两边的继续排序 在这里插入图片描述
而本题则远没有这么麻烦
只需要定义,左右 指针,依次往中间靠拢,最后不断交换 即可
代码如下

/**
 * 
 */

/***
 * @author 18071
 * @Date 2019年2月28日
 * 功能:  调整数组,使奇数再前,偶数再后
 ***/
public class test {

	public static void main(String args[]) {
		int[] x= {1,2,4,3,4,5,7,8,6,3};
		 sort(x);
		 
		 for(int i=0;i<x.length;i++) 
		 {
		 System.out.println(x[i]);
		 }
	}
	
	public static void sort(int [] x ) {
		int l=0;
		int r=x.length-1;
		
		while(l!=r&& l<=r) {
			System.out.println("now l is " +l);
			while(x[l]%2!=0) {
				
				l++;//不是偶数,向后移动 直到停在偶数的位置上
				
			}
			System.out.println("now r is " +r);
			while(x[r]%2==0) {
				
				r--;//不是奇数 ,向左移动 ,直到停在 奇数的位置上
			}
			int temp=x[l];
			x[l]=x[r];
			x[r]=temp;
			l++;
			r--;
			
			
		}
		
		
	}
	
}

结果如右图
在这里插入图片描述

此时,在这里回顾 快排

 public static void quickSort(int[] arr,int low,int high){
	        int i,j,temp,t;
	        
	        if(low>high){
	            return;
	        }
	        
	        i=low;
	        j=high;
	        //temp就是基准位
	        temp = arr[low];
	 
	        while (i<j) {
	            //先看右边,依次往左递减
	            while (temp<=arr[j]&&i<j) {
	                j--;
	            }
	            //再看左边,依次往右递增
	            while (temp>=arr[i]&&i<j) {
	                i++;
	            }
	            //如果满足条件则交换
	            if (i<j) {
	                t = arr[j];
	                arr[j] = arr[i];
	                arr[i] = t;
	            }
	 
	        }
		        //最后将基准为与i和j相等位置的数字交换
		         arr[low] = arr[i];
		         arr[i] = temp;
		        
		        quickSort(arr, low, j-1);
		      
		        quickSort(arr, j+1, high);
	    }

猜你喜欢

转载自blog.csdn.net/Hqxcsdn/article/details/88037819