Java数据结构 划分算法

来源:互联网 发布:教练记录课时软件 编辑:程序博客网 时间:2024/05/11 20:26

前言

       在现实生活中,当我们遇见好看的姑娘,我们很可能经验性的把她划分到美女一组里,而长相不那么给力的姑娘,分到别的组里,那么,分组的这么一个过程,其实就是划分算法,在划分算法里,我们往往需要一个pivot,来对姑娘进行分类,在这个例子中,pivot就是颜值

实现思路

  1. 用线性结构存储数据
  2. 定义数据两端点的指针,分别为leftPar和rightPar,他们指向数据的起始位置0,和数据的结束位置N
  3. leftPar不停向前移动,前提是指向的数据比pivot小并且leftPar小于数据的结束位置
  4. rightPar不停向后移动,前提是指向的数据比pivot大并且并且rightPar大于起始位置
  5. 进行判断左指针和右指针是否相交,如果是则跳出循环,算法结束,否则交换左指针和右指针的数据,循环以上

代码实现

public class PartitionItSort {//public static int theArr[]=new int []{13,2,4,1,22,31,5,7,8,9,15,17};public static int partition=10;public static void partitionitSort(int leftPar,int rightPar,int pivot){int left=leftPar-1;int right=rightPar+1;while(true){while(left<rightPar &&theArr[++left]<pivot);while(right>leftPar &&theArr[--right]>pivot);if(left>=right){break;}else{swap(left, right);}}return;}public static void display(){for(int i=0;i<theArr.length;i++){System.out.print(theArr[i]+" ");}}public static void swap(int a,int b){int temp;temp=theArr[a];theArr[a]=theArr[b];theArr[b]=temp;}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint leftPar=0;int rightPar=theArr.length;partitionitSort(0,rightPar-1,10);display();}}


0 0