Example usage for java.util Arrays sort

List of usage examples for java.util Arrays sort

Introduction

In this page you can find the example usage for java.util Arrays sort.

Prototype

public static <T> void sort(T[] a, Comparator<? super T> c) 

Source Link

Document

Sorts the specified array of objects according to the order induced by the specified comparator.

Usage

From source file:com.vsthost.rnd.jdeoptim.utils.Utils.java

/**
 * Returns the order of the values, ie. ordered indices sorted by comparing the elements of the array.
 *
 * @param values The vector of which the indices will be ordered.
 * @return The indices of the vector ordered according to sorted elements.
 *///from   w w w .  j a  v a 2  s.  c om
public static int[] order(final double[] values) {
    // Initialize the return vector:
    Integer[] vector = Utils.toObject(Utils.sequence(values.length));

    // Order:
    Arrays.sort(vector, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return Double.compare(values[o1], values[o2]);
        }
    });

    // Done, return indices:
    return Utils.toPrimitive(vector);
}

From source file:illab.nabal.util.ParameterHelper.java

/**
 * Sort parameters using lexicographical byte value ordering.
 * /*from   w w  w. j  a  v a 2 s .  com*/
 * @param params - list of parameters to sort
 * @return List<NameValuePair>
 */
public static List<NameValuePair> sortParams(List<NameValuePair> params) {
    NameValuePair[] sortedParams = params.toArray(new NameValuePair[params.size()]);
    Arrays.sort(sortedParams, paramComparator);
    params.clear();
    for (NameValuePair param : sortedParams) {
        params.add(param);
    }
    sortedParams = null;
    return params;
}

From source file:edu.umn.cs.spatialHadoop.indexing.BTRPartitioner.java

@Override
public void createFromPoints(Rectangle mbr, Point[] points, int capacity) {
    // Apply the STR algorithm in two rounds
    // 1- First round, sort points by X and split into the given columns
    Arrays.sort(points, new Comparator<Point>() {
        @Override//ww  w. j a  v  a2  s  .co  m
        public int compare(Point a, Point b) {
            return a.x < b.x ? -1 : (a.x > b.x ? 1 : 0);
        }
    });
    // Calculate partitioning numbers based on a grid
    int numSplits = (int) Math.ceil((double) points.length / capacity);
    GridInfo gridInfo = new GridInfo(mbr.x1, mbr.y1, mbr.x2, mbr.y2);
    gridInfo.calculateCellDimensions(numSplits);
    this.columns = gridInfo.columns;
    this.rows = gridInfo.rows;
    this.xSplits = new double[columns];
    this.ySplits = new double[rows * columns];
    int prev_quantile = 0;
    this.mbr.set(mbr);
    for (int column = 0; column < columns; column++) {
        int col_quantile = (column + 1) * points.length / columns;
        // Determine the x split for this column. Last column has a special handling
        this.xSplits[column] = col_quantile == points.length ? mbr.x2 : points[col_quantile - 1].x;
        // 2- Partition this column vertically in the same way
        Arrays.sort(points, prev_quantile, col_quantile, new Comparator<Point>() {
            @Override
            public int compare(Point a, Point b) {
                return a.y < b.y ? -1 : (a.y > b.y ? 1 : 0);
            }
        });
        // Compute y-splits for this column
        for (int row = 0; row < rows; row++) {
            int row_quantile = (prev_quantile * (rows - (row + 1)) + col_quantile * (row + 1)) / rows;
            // Determine y split for this row. Last row has a special handling
            this.ySplits[column * rows + row] = row_quantile == col_quantile ? mbr.y2 : points[row_quantile].y;
        }

        prev_quantile = col_quantile;
    }
}

From source file:net.sf.firemox.tools.MSaveDeck.java

/**
 * Saves deck to ASCII file from specified staticTurnLists. This new file will
 * contain the card names sorted in alphabetical order with their quantity
 * with this format :<br>/*from   w w w  .ja  v a  2 s .c o  m*/
 * <i>card's name </i> <b>; </b> <i>qty </i> <b>\n </b> <br>
 * 
 * @param fileName
 *          Name of new file.
 * @param names
 *          ListModel of card names.
 * @param parent
 *          the parent
 * @return true if the current deck has been correctly saved. false otherwise.
 */
public static boolean saveDeck(String fileName, MListModel<MCardCompare> names, JFrame parent) {
    PrintWriter outStream = null;
    try {
        // create the deckfile. If it was already existing, it would be scrathed.
        outStream = new PrintWriter(new FileOutputStream(fileName));
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(parent,
                "Cannot create/modify the specified deck file:" + fileName + "\n" + ex.getMessage(),
                "File creation problem", JOptionPane.ERROR_MESSAGE);
        return false;
    }

    Object[] namesArray = names.toArray();
    MCardCompare[] cards = new MCardCompare[namesArray.length];
    System.arraycopy(namesArray, 0, cards, 0, namesArray.length);

    // sorts names
    Arrays.sort(cards, new MCardCompare());
    // writes lines corresponding to this format : "card;quantity\n"
    for (int i = 0; i < cards.length; i++) {
        outStream.println(cards[i].toString());
    }
    IOUtils.closeQuietly(outStream);

    // successfull deck save
    JOptionPane.showMessageDialog(parent,
            "Saving file " + fileName.substring(fileName.lastIndexOf("/") + 1) + " was successfully completed.",
            "Save success", JOptionPane.INFORMATION_MESSAGE);
    return true;
}

From source file:com.naver.divideandconquer.closestpair.ClosestPair.java

private Pair getCenterClosestPair(Point[] points, double minDistance) {
    Point[] closestPairCandidatePoints = new Point[points.length];
    int count = 0;
    int mid = points.length / 2;
    Point standardPoint = points[mid];

    for (int i = 0; i < points.length; i++) {
        double distance = standardPoint.getX() > points[i].getX() ? standardPoint.getX() - points[i].getX()
                : points[i].getX() - standardPoint.getX();
        if (distance < minDistance) {
            closestPairCandidatePoints[count++] = points[i];
        }//from  www  . jav  a 2  s .co m
    }

    closestPairCandidatePoints = Arrays.copyOfRange(closestPairCandidatePoints, 0, count);

    Arrays.sort(closestPairCandidatePoints, Comparator.comparing(Point::getY));

    Pair centerClosestPair = null;
    for (int i = 0; i < closestPairCandidatePoints.length - 5; i++) {
        for (int j = i + 1; j < i + 6 && j < closestPairCandidatePoints.length; j++) {
            double distance = calculateDistance(closestPairCandidatePoints[i], closestPairCandidatePoints[j]);
            if (distance < minDistance) {
                Pair pair = new Pair(closestPairCandidatePoints[i], closestPairCandidatePoints[j], distance);
                centerClosestPair = pair;
            }
        }
    }

    return centerClosestPair;
}

From source file:net.myrrix.online.generation.InputFilesReader.java

static void readInputFiles(FastByIDMap<FastIDSet> knownItemIDs, FastByIDMap<FastByIDFloatMap> rbyRow,
        FastByIDMap<FastByIDFloatMap> rbyColumn, FastIDSet itemTagIDs, FastIDSet userTagIDs, File inputDir)
        throws IOException {

    FilenameFilter csvFilter = new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?");

    File[] otherFiles = inputDir.listFiles(new InvertedFilenameFilter(csvFilter));
    if (otherFiles != null) {
        for (File otherFile : otherFiles) {
            log.info("Skipping file {}", otherFile.getName());
        }//from w  w  w .j a  va2 s.  c om
    }

    File[] inputFiles = inputDir.listFiles(csvFilter);
    if (inputFiles == null) {
        log.info("No input files in {}", inputDir);
        return;
    }
    Arrays.sort(inputFiles, ByLastModifiedComparator.INSTANCE);

    IDMigrator hash = new OneWayMigrator();

    int lines = 0;
    int badLines = 0;
    for (File inputFile : inputFiles) {
        log.info("Reading {}", inputFile);
        for (String line : new FileLineIterable(inputFile)) {

            if (badLines > 100) { // Crude check
                throw new IOException("Too many bad lines; aborting");
            }

            lines++;

            if (line.isEmpty() || line.charAt(0) == '#') {
                continue;
            }

            Iterator<String> it = COMMA.split(line).iterator();

            long userID;
            boolean userIsTag;
            long itemID;
            boolean itemIsTag;
            float value;
            try {

                String userIDString = it.next();
                userIsTag = userIDString.startsWith("\"");
                if (userIsTag) {
                    userID = hash.toLongID(userIDString.substring(1, userIDString.length() - 1));
                } else {
                    userID = Long.parseLong(userIDString);
                }

                String itemIDString = it.next();
                itemIsTag = itemIDString.startsWith("\"");
                if (itemIsTag) {
                    itemID = hash.toLongID(itemIDString.substring(1, itemIDString.length() - 1));
                } else {
                    itemID = Long.parseLong(itemIDString);
                }

                if (it.hasNext()) {
                    String valueToken = it.next();
                    value = valueToken.isEmpty() ? Float.NaN : LangUtils.parseFloat(valueToken);
                } else {
                    value = 1.0f;
                }

            } catch (NoSuchElementException ignored) {
                log.warn("Ignoring line with too few columns: '{}'", line);
                badLines++;
                continue;
            } catch (IllegalArgumentException iae) { // includes NumberFormatException
                if (lines == 1) {
                    log.info("Ignoring header line: '{}'", line);
                } else {
                    log.warn("Ignoring unparseable line: '{}'", line);
                    badLines++;
                }
                continue;
            }

            if (userIsTag && itemIsTag) {
                log.warn("Two tags not allowed: '{}'", line);
                badLines++;
                continue;
            }

            if (userIsTag) {
                itemTagIDs.add(userID);
            }

            if (itemIsTag) {
                userTagIDs.add(itemID);
            }

            if (Float.isNaN(value)) {
                // Remove, not set
                MatrixUtils.remove(userID, itemID, rbyRow, rbyColumn);
            } else {
                MatrixUtils.addTo(userID, itemID, value, rbyRow, rbyColumn);
            }

            if (knownItemIDs != null) {
                FastIDSet itemIDs = knownItemIDs.get(userID);
                if (Float.isNaN(value)) {
                    // Remove, not set
                    if (itemIDs != null) {
                        itemIDs.remove(itemID);
                        if (itemIDs.isEmpty()) {
                            knownItemIDs.remove(userID);
                        }
                    }
                } else {
                    if (itemIDs == null) {
                        itemIDs = new FastIDSet();
                        knownItemIDs.put(userID, itemIDs);
                    }
                    itemIDs.add(itemID);
                }
            }

            if (lines % 1000000 == 0) {
                log.info("Finished {} lines", lines);
            }
        }
    }

    log.info("Pruning near-zero entries");
    removeSmall(rbyRow);
    removeSmall(rbyColumn);
}

From source file:net.sourceforge.jaulp.io.annotations.ImportResourcesUtils.java

/**
 * Gets a map with ImportResource objects and the corresponding to the found class from the
 * given package Name. The search is made recursive. The key from an entry of the map is the
 * class where the ImportResource objects found and the value is an Array of the ImportResource
 * objects that contains in the class./*ww  w  .  j a v  a 2  s.co m*/
 * 
 * @param packageName
 *            the package name
 * @return the import resources
 * @throws ClassNotFoundException
 *             the class not found exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Map<Class<?>, ImportResource[]> getImportResources(String packageName)
        throws ClassNotFoundException, IOException {
    final Map<Class<?>, ImportResource[]> resourcesMap = new LinkedHashMap<>();

    final Class<ImportResources> importResourcesClass = ImportResources.class;
    final Class<ImportResource> importResourceClass = ImportResource.class;
    final Set<Class<?>> importResourcesClasses = AnnotationUtils.getAllAnnotatedClasses(packageName,
            importResourcesClass);
    final Set<Class<?>> importResourceClasses = AnnotationUtils.getAllAnnotatedClasses(packageName,
            importResourceClass);
    importResourcesClasses.addAll(importResourceClasses);
    for (Class<?> annotatedClass : importResourcesClasses) {
        final ImportResources importResources = annotatedClass.getAnnotation(ImportResources.class);
        ImportResource[] importResourcesArray = null;
        ImportResource[] importResourceArray = null;
        if (importResources != null) {
            importResourcesArray = importResources.resources();
        }

        final ImportResource importResource = annotatedClass.getAnnotation(ImportResource.class);
        if (importResource != null) {
            importResourceArray = new ImportResource[1];
            importResourceArray[0] = importResource;
        }
        ImportResource[] array = (ImportResource[]) ArrayUtils.addAll(importResourceArray,
                importResourcesArray);
        Arrays.sort(array, new ImportResourceComparator());
        resourcesMap.put(annotatedClass, array);

    }
    return resourcesMap;
}

From source file:com.unister.semweb.drums.api.DRUMSIteratorTest.java

@Before
public void initialise() throws Exception {
    new File(TestUtils.gp.DATABASE_DIRECTORY).mkdirs();
    long[] ranges = new long[] { 0, 10, 20, 30 };
    byte[][] bRanges = KeyUtils.toByteArray(ranges);
    String[] filenames = new String[] { "1.db", "2", "3.db", "4.db" };
    FileUtils.deleteQuietly(new File(TestUtils.gp.DATABASE_DIRECTORY));
    this.hashFunction = new RangeHashFunction(bRanges, filenames, "/tmp/hash.hs");

    // fill with data
    table = DRUMSInstantiator.createTable(hashFunction, TestUtils.gp);
    // remember, the element with key 0 is ignored
    generatedData = TestUtils.createDummyData(1, 50);
    Arrays.sort(generatedData, new AbstractKVStorableComparator());
    table.insertOrMerge(generatedData);/*ww w  .j a v  a2  s  .c o  m*/
    table.close();
}

From source file:fr.fastconnect.factory.tibco.bw.codereview.CodeReviewInitialize.java

public File getTheNewestFile(File directory, String extension) {
    File newestFile = null;/*from www.  ja v  a2 s.  c o  m*/
    if (directory == null || !directory.exists() || !directory.isDirectory()) {
        return newestFile;
    }

    FileFilter fileFilter = new WildcardFileFilter("*." + extension);
    File[] files = directory.listFiles(fileFilter);

    if (files.length > 0) {
        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
        newestFile = files[0];
    }

    return newestFile;
}

From source file:com.mac.holdempoker.app.hands.Boat.java

private void insert(Card[] ranked, Card insert) {
    for (int i = 1; i < ranked.length; i++) {
        if (Objects.isNull(ranked[i])) {
            ranked[i] = insert;/*from  w  w  w. j  av  a 2s.  c om*/
            Arrays.sort(ranked, cardComparator());
            break;
        }
    }
}