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 void sort(Object[] a) 

Source Link

Document

Sorts the specified array of objects into ascending order, according to the Comparable natural ordering of its elements.

Usage

From source file:cop.raml.processor.rest.AbstractRestImpl.java

protected static String[] defOnNull(String... mediaTypes) {
    if (mediaTypes != null) {
        Arrays.sort(mediaTypes);
        return mediaTypes;
    }/*from w  w  w  . jav  a  2 s. c om*/

    String def = Config.get().apiMediaType();
    return def != null ? ArrayUtils.toArray(def) : null;
}

From source file:edu.umn.cs.spatialHadoop.operations.ClosestPair.java

/**
 * Finds the closest pair using an in-memory divide and conquer algorithm.
 * @param points// ww  w.  j  a v a2  s.  c  o m
 * @param threshold
 * @return
 */
public static Pair closestPairInMemory(final Point[] points, int threshold) {
    // Sort points by increasing x-axis
    Arrays.sort(points);

    class SubListComputation {
        int start, end;
        int p1, p2;
        double distance;
    }

    List<SubListComputation> sublists = new ArrayList<SubListComputation>();

    // Compute the closest pair for each sublist below the threshold
    int start = 0;
    while (start < points.length) {
        int end;
        if (start + (threshold * 3 / 2) > points.length)
            end = points.length;
        else
            end = start + threshold;
        SubListComputation closestPair = new SubListComputation();
        closestPair.start = start;
        closestPair.end = end;
        closestPair.p1 = start;
        closestPair.p2 = start + 1;
        closestPair.distance = points[start].distanceTo(points[start + 1]);

        for (int i1 = start; i1 < end; i1++) {
            for (int i2 = i1 + 1; i2 < end; i2++) {
                double distance = points[i1].distanceTo(points[i2]);
                if (distance < closestPair.distance) {
                    closestPair.p1 = i1;
                    closestPair.p2 = i2;
                    closestPair.distance = distance;
                }
            }
        }
        sublists.add(closestPair);
        start = end;
    }

    // Merge each pair of adjacent sublists
    while (sublists.size() > 1) {
        List<SubListComputation> newSublists = new ArrayList<SubListComputation>();
        for (int ilist = 0; ilist < sublists.size() - 1; ilist += 2) {
            SubListComputation list1 = sublists.get(ilist);
            SubListComputation list2 = sublists.get(ilist + 1);
            SubListComputation merged = new SubListComputation();
            merged.start = list1.start;
            merged.end = list2.end;
            // The closest pair of (list1 UNION list2) is either the closest pair
            // of list1, list2, or a new closest pair with one point in list1
            // and one point in list2
            double mindistance = Math.min(list1.distance, list2.distance);
            double xmin = points[list1.end - 1].x - mindistance;
            double xmax = points[list2.start].x + mindistance;
            int leftMargin = exponentialSearchLeft(points, list1.end, xmin);
            int rightMargin = exponentialSearchRight(points, list2.start, xmax);
            int minPointL = leftMargin, minPointR = list2.start;
            double minDistanceLR = points[minPointL].distanceTo(points[minPointR]);
            if (rightMargin - leftMargin < threshold) {
                // Use brute force technique
                for (int i1 = leftMargin; i1 < list1.end; i1++) {
                    for (int i2 = list2.start; i2 < rightMargin; i2++) {
                        double distance = points[i1].distanceTo(points[i2]);
                        if (distance < mindistance) {
                            minPointL = i1;
                            minPointR = i2;
                            minDistanceLR = distance;
                        }
                    }
                }
            } else {
                // Use a y-sort technique
                final int[] rPoints = new int[rightMargin - list2.start];
                for (int i = 0; i < rPoints.length; i++)
                    rPoints[i] = i + list2.start;
                IndexedSortable ysort = new IndexedSortable() {
                    @Override
                    public void swap(int i, int j) {
                        int temp = rPoints[i];
                        rPoints[i] = rPoints[j];
                        rPoints[j] = temp;
                    }

                    @Override
                    public int compare(int i, int j) {
                        double dy = points[rPoints[i]].y - points[rPoints[j]].y;
                        if (dy < 0)
                            return -1;
                        if (dy > 0)
                            return 1;
                        return 0;
                    }
                };
                new QuickSort().sort(ysort, 0, rPoints.length);
                int rpoint1 = 0, rpoint2 = 0;
                for (int ilPoint = leftMargin; ilPoint < list1.end; ilPoint++) {
                    Point lPoint = points[ilPoint];
                    while (rpoint1 < rPoints.length && lPoint.y - points[rPoints[rpoint1]].y > mindistance)
                        rpoint1++;
                    while (rpoint2 < rPoints.length && points[rPoints[rpoint2]].y - lPoint.y < mindistance)
                        rpoint2++;
                    for (int rpoint = rpoint1; rpoint < rpoint2; rpoint++) {
                        double distance = lPoint.distanceTo(points[rPoints[rpoint]]);
                        if (distance < minDistanceLR) {
                            minPointL = ilPoint;
                            minPointR = rPoints[rpoint];
                            minDistanceLR = distance;
                        }
                    }
                }
            }

            if (minDistanceLR < mindistance) {
                // The closest pair is in the middle (between list1 and list2)
                merged.distance = minDistanceLR;
                merged.p1 = minPointL;
                merged.p2 = minPointR;
            } else if (list1.distance < list2.distance) {
                // The closest pair is in list1
                merged.distance = list1.distance;
                merged.p1 = list1.p1;
                merged.p2 = list1.p2;
            } else {
                // The closest pair is in list2
                merged.distance = list2.distance;
                merged.p1 = list2.p1;
                merged.p2 = list2.p2;
            }

            newSublists.add(merged);
        }
        sublists = newSublists;
    }

    Pair closestPair = new Pair();
    closestPair.p1 = points[sublists.get(0).p1];
    closestPair.p2 = points[sublists.get(0).p2];
    return closestPair;
}

From source file:fi.smaa.libror.RejectionValueFunctionSampler.java

private void sampleRandomPartialVF(PartialValueFunction pvf) {
    double[] vals = pvf.getValues();
    for (int i = 1; i < vals.length - 1; i++) {
        vals[i] = RandomUtil.createUnif01();
    }/*from  w w w.  jav a  2s. co  m*/
    Arrays.sort(vals);
}

From source file:fi.smaa.common.RandomUtil.java

/**
 * Creates an array of random numbers that sum to a given amount.
 * /*  w  w w  .j  a v a 2 s. co m*/
 * @param dest the array to create the numbers to.
 * @param sumTo The amount the numbers must sum to. Must be >= 0.0
 * @throws NullPointerException if dest == null
 */
public void createSumToRand(double[] dest, double sumTo) throws NullPointerException {
    assert (sumTo >= 0.0);
    if (dest == null) {
        throw new NullPointerException("destination array null");
    }

    int len = dest.length;
    for (int i = 0; i < len - 1; i++) {
        dest[i] = createUnif01() * sumTo;
    }

    dest[len - 1] = sumTo;

    Arrays.sort(dest);

    double last = 0.0;
    for (int i = 0; i < len; i++) {
        double t = dest[i];
        dest[i] = t - last;
        last = t;
    }
}

From source file:com.alibaba.sample.petstore.dal.dao.ProductItemDaoTests.java

private void assertProductItemList(List<ProductItem> items, String... ids) {
    String[] result = new String[items.size()];

    int i = 0;//from   w  w  w  . j a  v  a  2s.co  m
    for (ProductItem item : items) {
        result[i++] = item.getProductItemId();
    }

    Arrays.sort(result);
    Arrays.sort(ids);

    assertArrayEquals(ids, result);
}

From source file:de.banapple.maven.antlr.SyntaxDiagramMojo.java

/**
 * Creates an index file in the output directory containing all
 * generated images.//from   www  .  j a  v a  2 s  .  co m
 */
private void createIndex() {
    /* retrieve all png files */
    String[] imageFilenames = outputDirectory.list(new FilenameFilter() {
        public boolean accept(File dir, String filename) {
            return filename.endsWith("png");
        }
    });

    /* sort filenames by lower case first */
    Arrays.sort(imageFilenames);

    StringBuilder content = new StringBuilder();
    content.append("<html>");
    content.append("<body>");

    /* table of contents */
    content.append("<a name=\"top\" />");
    content.append("<ol>");
    for (String filename : imageFilenames) {
        String name = filename.substring(0, filename.length() - 4);
        content.append("<li>").append("<a href=\"#").append(name).append("\">").append(name).append("</a>")
                .append("</li>");
    }
    content.append("</ol>");

    /* images */
    for (String filename : imageFilenames) {
        String name = filename.substring(0, filename.length() - 4);
        content.append("<h2>").append(name).append("</h2>");
        content.append("<a name=\"").append(name).append("\" />");
        content.append("<img src=\"").append(filename).append("\" />");
        content.append("<br/><a href=\"#top\">up</a>");
    }
    content.append("</body>");
    content.append("</html>");

    File indexFile = new File(outputDirectory, "index.html");
    try {
        IOUtils.write(content.toString(), new FileOutputStream(indexFile));
    } catch (Exception e) {
        getLog().error("failed to generate index file", e);
        throw new RuntimeException(e);
    }
}

From source file:com.wikonos.fingerprint.activities.MainActivity.java

/**
 * Create dialog list of logs/*from w  w  w .jav a  2  s  .  c  om*/
 * 
 * @return
 */
public AlertDialog getDialogReviewLogs() {
    /**
     * List of logs
     */
    File folder = new File(LogWriter.APPEND_PATH);
    final String[] files = folder.list(new FilenameFilter() {
        public boolean accept(File dir, String filename) {
            if (filename.contains(".log") && !filename.equals(LogWriter.DEFAULT_NAME)
                    && !filename.equals(LogWriterSensors.DEFAULT_NAME)
                    && !filename.equals(ErrorLog.DEFAULT_NAME))
                return true;
            else
                return false;
        }
    });

    Arrays.sort(files);
    ArrayUtils.reverse(files);

    String[] files_with_status = new String[files.length];
    String[] sent_mode = { "", "(s) ", "(e) ", "(s+e) " };
    for (int i = 0; i < files.length; ++i) {
        //0 -- not sent
        //1 -- server
        //2 -- email
        files_with_status[i] = sent_mode[getSentFlags(files[i], this)] + files[i];
    }

    if (files != null && files.length > 0) {

        final boolean[] selected = new boolean[files.length];

        final AlertDialog ald = new AlertDialog.Builder(MainActivity.this)
                .setMultiChoiceItems(files_with_status, selected,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                selected[which] = isChecked;
                            }
                        })
                .setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        // removeDialog(DIALOG_ID_REVIEW);
                    }
                })
                /**
                * Delete log
                */
                .setNegativeButton("Delete", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        //Show delete confirm
                        standardConfirmDialog("Delete Logs", "Are you sure you want to delete selected logs?",
                                new OnClickListener() {
                                    //Confrim Delete
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        int deleteCount = 0;
                                        boolean flagSelected = false;
                                        for (int i = 0; i < selected.length; i++) {
                                            if (selected[i]) {
                                                flagSelected = true;
                                                LogWriter.delete(files[i]);
                                                LogWriter.delete(files[i].replace(".log", ".dev"));
                                                deleteCount++;
                                            }
                                        }

                                        reviewLogsCheckItems(flagSelected);

                                        removeDialog(DIALOG_ID_REVIEW);

                                        Toast.makeText(getApplicationContext(), deleteCount + " logs deleted.",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }, new OnClickListener() {
                                    //Cancel Delete
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //Do nothing
                                        dialog.dismiss();
                                        Toast.makeText(getApplicationContext(), "Delete cancelled.",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }, false);
                    }
                })
                /**
                * Send to server functional
                **/
                .setNeutralButton("Send to Server", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (isOnline()) {
                            ArrayList<String> filesList = new ArrayList<String>();

                            for (int i = 0; i < selected.length; i++)
                                if (selected[i]) {

                                    filesList.add(LogWriter.APPEND_PATH + files[i]);
                                    //Move to httplogsender
                                    //setSentFlags(files[i], 1, MainActivity.this);   //Mark file as sent
                                }

                            if (reviewLogsCheckItems(filesList.size() > 0 ? true : false)) {
                                DataPersistence d = new DataPersistence(getApplicationContext());
                                new HttpLogSender(MainActivity.this,
                                        d.getServerName() + getString(R.string.submit_log_url), filesList)
                                                .setToken(getToken()).execute();
                            }

                            // removeDialog(DIALOG_ID_REVIEW);
                        } else {
                            standardAlertDialog(getString(R.string.msg_alert),
                                    getString(R.string.msg_no_internet), null);
                        }
                    }
                })
                /**
                * Email
                **/
                .setPositiveButton("eMail", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        boolean flagSelected = false;
                        // convert from paths to Android friendly
                        // Parcelable Uri's
                        ArrayList<Uri> uris = new ArrayList<Uri>();
                        for (int i = 0; i < selected.length; i++)
                            if (selected[i]) {
                                flagSelected = true;
                                /** wifi **/
                                File fileIn = new File(LogWriter.APPEND_PATH + files[i]);
                                Uri u = Uri.fromFile(fileIn);
                                uris.add(u);

                                /** sensors **/
                                File fileInSensors = new File(
                                        LogWriter.APPEND_PATH + files[i].replace(".log", ".dev"));
                                Uri uSens = Uri.fromFile(fileInSensors);
                                uris.add(uSens);

                                setSentFlags(files[i], 2, MainActivity.this); //Mark file as emailed
                            }

                        if (reviewLogsCheckItems(flagSelected)) {
                            /**
                             * Run sending email activity
                             */
                            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
                            emailIntent.setType("plain/text");
                            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                                    "Wifi Searcher Scan Log");
                            emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                            startActivity(Intent.createChooser(emailIntent, "Send mail..."));
                        }

                        // removeDialog(DIALOG_ID_REVIEW);
                    }
                }).create();

        ald.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                AlertDialog segmentNameAlert = segmentNameDailog("Rename Segment", ald.getContext(),
                        files[position], null, view, files, position);
                segmentNameAlert.setCanceledOnTouchOutside(false);
                segmentNameAlert.show();
                return false;
            }
        });
        return ald;
    } else {
        return standardAlertDialog(getString(R.string.msg_alert), getString(R.string.msg_log_nocount),
                new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        removeDialog(DIALOG_ID_REVIEW);
                    }
                });
    }
}

From source file:com.linkedin.pinot.core.segment.index.readers.ImmutableDictionaryReaderTest.java

@BeforeClass
public void setUp() throws Exception {
    FileUtils.deleteQuietly(TEMP_DIR);/*from w w w.ja v a 2  s  .  c  o m*/

    IntOpenHashSet intSet = new IntOpenHashSet();
    while (intSet.size() < NUM_VALUES) {
        intSet.add(RANDOM.nextInt());
    }
    _intValues = intSet.toIntArray();
    Arrays.sort(_intValues);

    LongOpenHashSet longSet = new LongOpenHashSet();
    while (longSet.size() < NUM_VALUES) {
        longSet.add(RANDOM.nextLong());
    }
    _longValues = longSet.toLongArray();
    Arrays.sort(_longValues);

    FloatOpenHashSet floatSet = new FloatOpenHashSet();
    while (floatSet.size() < NUM_VALUES) {
        floatSet.add(RANDOM.nextFloat());
    }
    _floatValues = floatSet.toFloatArray();
    Arrays.sort(_floatValues);

    DoubleOpenHashSet doubleSet = new DoubleOpenHashSet();
    while (doubleSet.size() < NUM_VALUES) {
        doubleSet.add(RANDOM.nextDouble());
    }
    _doubleValues = doubleSet.toDoubleArray();
    Arrays.sort(_doubleValues);

    Set<String> stringSet = new HashSet<>();
    while (stringSet.size() < NUM_VALUES) {
        stringSet.add(RandomStringUtils.random(RANDOM.nextInt(MAX_STRING_LENGTH)).replace('\0', ' '));
    }
    _stringValues = stringSet.toArray(new String[NUM_VALUES]);
    Arrays.sort(_stringValues);

    try (SegmentDictionaryCreator dictionaryCreator = new SegmentDictionaryCreator(_intValues,
            new DimensionFieldSpec(INT_COLUMN_NAME, FieldSpec.DataType.INT, true), TEMP_DIR)) {
        dictionaryCreator.build();
    }

    try (SegmentDictionaryCreator dictionaryCreator = new SegmentDictionaryCreator(_longValues,
            new DimensionFieldSpec(LONG_COLUMN_NAME, FieldSpec.DataType.LONG, true), TEMP_DIR)) {
        dictionaryCreator.build();
    }

    try (SegmentDictionaryCreator dictionaryCreator = new SegmentDictionaryCreator(_floatValues,
            new DimensionFieldSpec(FLOAT_COLUMN_NAME, FieldSpec.DataType.FLOAT, true), TEMP_DIR)) {
        dictionaryCreator.build();
    }

    try (SegmentDictionaryCreator dictionaryCreator = new SegmentDictionaryCreator(_doubleValues,
            new DimensionFieldSpec(DOUBLE_COLUMN_NAME, FieldSpec.DataType.DOUBLE, true), TEMP_DIR)) {
        dictionaryCreator.build();
    }

    try (SegmentDictionaryCreator dictionaryCreator = new SegmentDictionaryCreator(_stringValues,
            new DimensionFieldSpec(STRING_COLUMN_NAME, FieldSpec.DataType.STRING, true), TEMP_DIR)) {
        dictionaryCreator.build();
        _numBytesPerStringValue = dictionaryCreator.getNumBytesPerString();
    }
}

From source file:com.feedzai.fos.api.CategoricalAttribute.java

/**
 * Creates a new categorical with the given <code>name</code>, <code>type</code> and <code>categoricalInstances</code>.
 * <p/> The <code>categoricalInstances</code> is the set of possible values that the field can take.
 *
 * @param name                  the name of the field
 * @param pcategoricalInstances for <code>type=nominal</code>, defines the possibles values of the field
 *///from   w  w w  .ja  v a 2  s. c  om
@JsonCreator
public CategoricalAttribute(@NotBlank @JsonProperty("name") String name,
        @JsonProperty("categoricalInstances") List<String> pcategoricalInstances) {
    super(name);

    checkArgument(pcategoricalInstances != null && pcategoricalInstances.size() > 0,
            "Missing instances for nominal value");
    checkArgument(!pcategoricalInstances.contains(""), "Nominal instances values must not empty");
    checkArgument(!pcategoricalInstances.contains(null), "Nominal instances must not be null");

    String[] sorted = pcategoricalInstances.toArray(new String[pcategoricalInstances.size()]);
    Arrays.sort(sorted);

    this.categoricalInstances = ImmutableList.copyOf(sorted);
}

From source file:com.blockwithme.longdb.test.BETableJUnit.java

/** Sort desending. */
private static long[] sortDesending(final long[] theArray) {
    Arrays.sort(theArray);
    final int count = theArray.length;
    if (count > 1) {
        final int stop = count / 2;
        final int top = count - 1;
        for (int i = 0; i < stop; i++) {
            final long tmp = theArray[i];
            final int other = top - i;
            theArray[i] = theArray[other];
            theArray[other] = tmp;/*from w  ww  . java 2s  .c om*/
        }
    }
    return theArray;
}