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:LotteryDrawing.java

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    System.out.print("How many numbers do you need to draw? ");
    int k = in.nextInt();

    System.out.print("What is the highest number you can draw? ");
    int n = in.nextInt();

    // fill an array with numbers 1 2 3 . . . n
    int[] numbers = new int[n];
    for (int i = 0; i < numbers.length; i++)
        numbers[i] = i + 1;//  www  .jav  a  2s . c  om

    // draw k numbers and put them into a second array
    int[] result = new int[k];
    for (int i = 0; i < result.length; i++) {
        // make a random index between 0 and n - 1
        int r = (int) (Math.random() * n);

        // pick the element at the random location
        result[i] = numbers[r];

        // move the last element into the random location
        numbers[r] = numbers[n - 1];
        n--;
    }

    // print the sorted array
    Arrays.sort(result);
    System.out.println("Bet the following combination. It'll make you rich!");
    for (int r : result)
        System.out.println(r);
}

From source file:mase.deprecated.SelectionBenchmark.java

public static void main(String[] args) {

    int L = 100, N = 10000;
    double[] truncationP = new double[] { 0.25, 0.50, 0.75 };
    int[] tournamentP = new int[] { 2, 5, 7, 10 };

    DescriptiveStatistics[] truncationStat = new DescriptiveStatistics[truncationP.length];
    for (int i = 0; i < truncationStat.length; i++) {
        truncationStat[i] = new DescriptiveStatistics();
    }//from w  w  w . ja va 2s  .  c o  m
    DescriptiveStatistics[] tournamentStat = new DescriptiveStatistics[tournamentP.length];
    DescriptiveStatistics[] tournamentStat2 = new DescriptiveStatistics[tournamentP.length];
    for (int i = 0; i < tournamentStat.length; i++) {
        tournamentStat[i] = new DescriptiveStatistics();
        tournamentStat2[i] = new DescriptiveStatistics();
    }
    DescriptiveStatistics rouletteStat = new DescriptiveStatistics();
    DescriptiveStatistics rouletteStat2 = new DescriptiveStatistics();
    DescriptiveStatistics baseStat = new DescriptiveStatistics();

    for (int i = 0; i < N; i++) {
        // generate test vector
        double[] test = new double[L];
        for (int j = 0; j < L; j++) {
            test[j] = Math.random();
        }

        // truncation
        for (int p = 0; p < truncationP.length; p++) {
            double[] v = Arrays.copyOf(test, test.length);
            Arrays.sort(v);
            int nElites = (int) Math.ceil(truncationP[p] * test.length);
            double cutoff = v[test.length - nElites];
            double[] weights = new double[test.length];
            for (int k = 0; k < test.length; k++) {
                weights[k] = test[k] >= cutoff ? test[k] * (1 / truncationP[p]) : 0;
            }
            truncationStat[p].addValue(sum(weights));
        }

        // tournament
        for (int p = 0; p < tournamentP.length; p++) {
            double[] weights = new double[test.length];
            HashSet<Integer> added = new HashSet<Integer>();
            for (int k = 0; k < test.length; k++) {
                int idx = makeTournament(test, tournamentP[p]);
                weights[idx] += test[idx];
                added.add(idx);
            }
            tournamentStat2[p].addValue(added.size());
            tournamentStat[p].addValue(sum(weights));
        }

        // roulette
        double[] weights = new double[test.length];
        HashSet<Integer> added = new HashSet<Integer>();
        for (int k = 0; k < test.length; k++) {
            int idx = roulette(test);
            weights[idx] += test[idx];
            added.add(idx);
        }
        rouletteStat.addValue(sum(weights));
        rouletteStat2.addValue(added.size());

        // base
        baseStat.addValue(sum(test));
    }

    for (int p = 0; p < truncationP.length; p++) {
        System.out.println("Truncation\t" + truncationP[p] + "\t" + truncationStat[p].getMean() + "\t"
                + truncationStat[p].getStandardDeviation() + "\t" + ((int) Math.ceil(L * truncationP[p]))
                + "\t 0");
    }
    for (int p = 0; p < tournamentP.length; p++) {
        System.out.println("Tournament\t" + tournamentP[p] + "\t" + tournamentStat[p].getMean() + "\t"
                + tournamentStat[p].getStandardDeviation() + "\t" + tournamentStat2[p].getMean() + "\t"
                + tournamentStat2[p].getStandardDeviation());
    }
    System.out.println("Roulette\t\t" + rouletteStat.getMean() + "\t" + rouletteStat.getStandardDeviation()
            + "\t" + rouletteStat2.getMean() + "\t" + rouletteStat2.getStandardDeviation());
    System.out.println(
            "Base    \t\t" + baseStat.getMean() + "\t" + baseStat.getStandardDeviation() + "\t " + L + "\t0");
}

From source file:Snippet151.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.BORDER | SWT.VIRTUAL);
    table.addListener(SWT.SetData, new Listener() {
        public void handleEvent(Event e) {
            TableItem item = (TableItem) e.item;
            int index = table.indexOf(item);
            item.setText("Item " + data[index]);
        }/*from  w ww .j  a v  a  2  s  .c o m*/
    });
    Thread thread = new Thread() {
        public void run() {
            int count = 0;
            Random random = new Random();
            while (count++ < 500) {
                if (table.isDisposed())
                    return;
                // add 10 random numbers to array and sort
                int grow = 10;
                int[] newData = new int[data.length + grow];
                System.arraycopy(data, 0, newData, 0, data.length);
                int index = data.length;
                data = newData;
                for (int j = 0; j < grow; j++) {
                    data[index++] = random.nextInt();
                }
                Arrays.sort(data);
                display.syncExec(new Runnable() {
                    public void run() {
                        if (table.isDisposed())
                            return;
                        table.setItemCount(data.length);
                        table.clearAll();
                    }
                });
                try {
                    Thread.sleep(500);
                } catch (Throwable t) {
                }
            }
        }
    };
    thread.start();
    shell.open();
    while (!shell.isDisposed() || thread.isAlive()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:Main.java

  public static void main(String[] args) {
  int intArray[] = { 1, 2, 4, 5 };
  Arrays.sort(intArray);
  int searchValue = 2;
  System.out.println(Arrays.binarySearch(intArray, searchValue));

  searchValue = 3;/*  ww  w.  j  ava 2s  .c o  m*/
  System.out.println(Arrays.binarySearch(intArray, searchValue));
}

From source file:org.eclipse.swt.snippets.Snippet151.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 151");
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.BORDER | SWT.VIRTUAL);
    table.addListener(SWT.SetData, e -> {
        TableItem item = (TableItem) e.item;
        int index = table.indexOf(item);
        item.setText("Item " + data[index]);
    });//from  w  w  w.j a v a2  s  .c  om
    Thread thread = new Thread() {
        @Override
        public void run() {
            int count = 0;
            Random random = new Random();
            while (count++ < 500) {
                if (table.isDisposed())
                    return;
                // add 10 random numbers to array and sort
                int grow = 10;
                int[] newData = new int[data.length + grow];
                System.arraycopy(data, 0, newData, 0, data.length);
                int index = data.length;
                data = newData;
                for (int j = 0; j < grow; j++) {
                    data[index++] = random.nextInt();
                }
                Arrays.sort(data);
                display.syncExec(() -> {
                    if (table.isDisposed())
                        return;
                    table.setItemCount(data.length);
                    table.clearAll();
                });
                try {
                    Thread.sleep(500);
                } catch (Throwable t) {
                }
            }
        }
    };
    thread.start();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:at.tuwien.ifs.somtoolbox.apps.helper.VectorFileLabelLister.java

public static void main(String[] args) throws IOException {
    // register and parse all options
    JSAPResult config = OptionFactory.parseResults(args, OPTIONS);

    String inputVectorFileName = AbstractOptionFactory.getFilePath(config, "input");
    String outputFileName = AbstractOptionFactory.getFilePath(config, "output");

    PrintStream out;//  ww w .  ja  va  2s .c  o  m
    if (StringUtils.isBlank(outputFileName)) {
        out = System.out;
    } else {
        out = new PrintStream(outputFileName);
    }

    InputData data = InputDataFactory.open(inputVectorFileName);
    String[] labels = data.getLabels();
    Arrays.sort(labels);
    for (String s : labels) {
        out.println(s);
    }
    out.close();
}

From source file:SortBooleans.java

public static void main(String[] unused) {
    Boolean[] data = { new Boolean(true), new Boolean(false), new Boolean(false), new Boolean(true), };
    Arrays.sort(data); // EXPECT RUNTIME ERROR
    for (int i = 0; i < data.length; i++)
        System.out.println(data[i]);
}

From source file:com.garyclayburg.BootVaadin.java

public static void main(String[] args) {
    log.info("running main with args: " + Arrays.toString(args));
    ensureActiveProfile();/*w  ww  . j a va2s . c o  m*/
    ApplicationContext ctx = SpringApplication.run(BootUp.class, args);
    log.info("active profiles: " + Arrays.toString(ctx.getEnvironment().getActiveProfiles()));

    log.info("Beans loaded by spring / spring boot");
    String[] beanNames = ctx.getBeanDefinitionNames();
    Arrays.sort(beanNames);
    for (String beanName : beanNames) {
        log.info(beanName);
    }
    log.info("");
    log.info("BootVaadin Server is ready for e-business");

}

From source file:Main.java

  public static void main(String[] args) {
  long longArray[] = { 1L, 2L, 4L, 5L };
  Arrays.sort(longArray);

  long searchValue = 2L;
  System.out.println(Arrays.binarySearch(longArray, searchValue));

  searchValue = 3;/*from   ww  w  .  j  a v a 2s.co  m*/
  System.out.println(Arrays.binarySearch(longArray, searchValue));
}

From source file:com.linkedin.pinotdruidbenchmark.PinotResponseTime.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
        System.err.println(/*www .  j  av  a 2s. co  m*/
                "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    int warmUpRounds = Integer.parseInt(args[2]);
    int testRounds = Integer.parseInt(args[3]);
    File resultDir;
    if (args.length == 4) {
        resultDir = null;
    } else {
        resultDir = new File(args[4]);
        if (!resultDir.exists()) {
            if (!resultDir.mkdirs()) {
                throw new RuntimeException("Failed to create result directory: " + resultDir);
            }
        }
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(resourceUrl);

        for (File queryFile : queryFiles) {
            String query = new BufferedReader(new FileReader(queryFile)).readLine();
            httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));

            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Running query: " + query);
            System.out.println(
                    "--------------------------------------------------------------------------------");

            // Warm-up Rounds
            System.out.println("Run " + warmUpRounds + " times to warm up...");
            for (int i = 0; i < warmUpRounds; i++) {
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            System.out.println("Run " + testRounds + " times to get response time statistics...");
            long[] responseTimes = new long[testRounds];
            long totalResponseTime = 0L;
            for (int i = 0; i < testRounds; i++) {
                long startTime = System.currentTimeMillis();
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                long responseTime = System.currentTimeMillis() - startTime;
                responseTimes[i] = responseTime;
                totalResponseTime += responseTime;
                System.out.print(responseTime + "ms ");
            }
            System.out.println();

            // Store result.
            if (resultDir != null) {
                File resultFile = new File(resultDir, queryFile.getName() + ".result");
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
                        httpResponse.getEntity().getContent());
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) {
                    int length;
                    while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) {
                        bufferedWriter.write(new String(BYTE_BUFFER, 0, length));
                    }
                }
                httpResponse.close();
            }

            // Process response times.
            double averageResponseTime = (double) totalResponseTime / testRounds;
            double temp = 0;
            for (long responseTime : responseTimes) {
                temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime);
            }
            double standardDeviation = Math.sqrt(temp / testRounds);
            System.out.println("Average response time: " + averageResponseTime + "ms");
            System.out.println("Standard deviation: " + standardDeviation);
        }
    }
}