zoukankan      html  css  js  c++  java
  • 快速排序一(划分)

    目标:在一组数a0,a1,a2,a3,a4,a5,a6,a7,a8,a9中尽量取其中间值,以此为pivot,值大于pivot的元素置于pivot左边,反之至于右边。

    源代码:

    package com.paixu;

    public class ArrayPar {
    private int nElems;
    private long[] arr;
    public ArrayPar(int max){
    arr = new long[max];
    nElems =0;
    }
    public void insert(long value){
    arr[nElems++] = value;
    }

    public void display(){
    for(int i=0;i<nElems;i++)
    System.out.print("the" + i + "Elem is " + arr[i] + " " );
    }

    public int size(){
    return nElems;
    }

    public int partitionIt(int left,int right,int pivot){
    int leftPtr = left -1;
    int rightPtr = right + 1;

    while(true){
    while(leftPtr < right && arr[++leftPtr] < pivot)
    ;
    while(rightPtr > left && arr[--rightPtr] > pivot)
    ;
    if(leftPtr >= rightPtr)
    break;
    else
    swap(leftPtr,rightPtr);
    }
    return leftPtr;
    }

    public void swap(int leftValue,int rightValue){
    long temp;
    temp =arr[rightValue];
    arr[rightValue] = arr[leftValue];
    arr[leftValue] = temp;
    }
    }

    package com.paixu;

    public class PartitionApp {

    public static void main(String[] args){
    int maxSize = 20;
    ArrayPar arr = new ArrayPar(maxSize);

    for(int i=0;i<maxSize;i++){
    long n = (long)(Math.random() * 99);
    arr.insert(n);
    }
    arr.display();
    System.out.println();
    int pivor = 50;
    int size = arr.size();
    int partDex = arr.partitionIt(0, size-1, pivor);
    System.out.println("Partition is at index " + partDex);
    arr.display();
    }

    }

  • 相关阅读:
    A*算法实现 八数码问题
    poj 1077 Eight(bfs,dbfs, A*)
    poj 1729 Jack and Jill (搜索,bfs)
    poj 4105 拯救公主(bfs)
    poj4091The Closest M Points(KD-tree)
    资源整理
    推荐 VS2010入门教程—鸡啄米
    Cstring的使用
    VC 中TEXT、_T、L的区别
    电脑内存和CPU的关系
  • 原文地址:https://www.cnblogs.com/xunmengyoufeng/p/2712766.html
Copyright © 2011-2022 走看看