Java Code Examples for java.util.Arrays#sort()

The following examples show how to use java.util.Arrays#sort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Sorting.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static void sort(Object object) {
    if (object instanceof int[]) {
        Arrays.sort((int[]) object);
    } else if (object instanceof long[]) {
        Arrays.sort((long[]) object);
    } else if (object instanceof short[]) {
        Arrays.sort((short[]) object);
    } else if (object instanceof byte[]) {
        Arrays.sort((byte[]) object);
    } else if (object instanceof char[]) {
        Arrays.sort((char[]) object);
    } else if (object instanceof float[]) {
        Arrays.sort((float[]) object);
    } else if (object instanceof double[]) {
        Arrays.sort((double[]) object);
    } else if (object instanceof Integer[]) {
        Arrays.sort((Integer[]) object);
    } else {
        failed("Unknow type of array: " + object + " of class " +
            object.getClass().getName());
    }
}
 
Example 2
Source File: TestCharsRef.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public void testUTF16InUTF8Order() {
  final int numStrings = atLeast(1000);
  BytesRef utf8[] = new BytesRef[numStrings];
  CharsRef utf16[] = new CharsRef[numStrings];
  
  for (int i = 0; i < numStrings; i++) {
    String s = TestUtil.randomUnicodeString(random());
    utf8[i] = new BytesRef(s);
    utf16[i] = new CharsRef(s);
  }
  
  Arrays.sort(utf8);
  Arrays.sort(utf16, CharsRef.getUTF16SortedAsUTF8Comparator());
  
  for (int i = 0; i < numStrings; i++) {
    assertEquals(utf8[i].utf8ToString(), utf16[i].toString());
  }
}
 
Example 3
Source File: PropertyEditorPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void removeRowButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRowButtonActionPerformed
    int[] viewRows = propertyTable.getSelectedRows();
    int[] modelRows = new int[viewRows.length];

    for (int i = 0; i < viewRows.length; i++) {
        modelRows[i] = propertyTable.convertRowIndexToModel(viewRows[i]);
    }

    Arrays.sort(modelRows);

    DefaultTableModel dtm = (DefaultTableModel) propertyTable.getModel();

    for (int i = modelRows.length - 1; i >= 0; i--) {
        dtm.removeRow(modelRows[i]);
    }
}
 
Example 4
Source File: MathUtil.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@Description("Returns the minimum of the int values<br/>" +
        "<b>numbers</b> - integer values for comparison<br/>" +
        "Example:<br/>" +
        "#{minInt(5, 4, 3)} returns 3")
@UtilityMethod
public int minInt(int ... numbers){
    Arrays.sort(numbers);
    return numbers[0];
}
 
Example 5
Source File: SortedOps.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void end() {
    double[] doubles = b.asPrimitiveArray();
    Arrays.sort(doubles);
    downstream.begin(doubles.length);
    for (double aDouble : doubles)
        downstream.accept(aDouble);
    downstream.end();
}
 
Example 6
Source File: BOSSSpatialPyramids_BD.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
protected double[][] MCB(Instances data) {
    double[][][] dfts = new double[data.numInstances()][][];

    int sample = 0;
    for (Instance inst : data) {
        dfts[sample++] = performDFT(disjointWindows(toArrayNoClass(inst))); //approximation
    }

    int numInsts = dfts.length;
    int numWindowsPerInst = dfts[0].length;
    int totalNumWindows = numInsts*numWindowsPerInst;

    breakpoints = new double[wordLength][alphabetSize]; 

    for (int letter = 0; letter < wordLength; ++letter) { //for each dft coeff

        //extract this column from all windows in all instances
        double[] column = new double[totalNumWindows];
        for (int inst = 0; inst < numInsts; ++inst)
            for (int window = 0; window < numWindowsPerInst; ++window) {
                //rounding dft coefficients to reduce noise
                column[(inst * numWindowsPerInst) + window] = Math.round(dfts[inst][window][letter]*100.0)/100.0;   
            }

        //sort, and run through to find breakpoints for equi-depth bins
        Arrays.sort(column);

        double binIndex = 0;
        double targetBinDepth = (double)totalNumWindows / (double)alphabetSize; 

        for (int bp = 0; bp < alphabetSize-1; ++bp) {
            binIndex += targetBinDepth;
            breakpoints[letter][bp] = column[(int)binIndex];
        }

        breakpoints[letter][alphabetSize-1] = Double.MAX_VALUE; //last one can always = infinity
    }

    return breakpoints;
}
 
Example 7
Source File: RemoteClass.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new Method instance for the specified method.
 **/
Method(MethodDoc methodDoc) {
    this.methodDoc = methodDoc;
    exceptionTypes = methodDoc.thrownExceptions();
    /*
     * Sort exception types to improve consistency with
     * previous implementations.
     */
    Arrays.sort(exceptionTypes, new ClassDocComparator());
    operationString = computeOperationString();
    nameAndDescriptor =
        methodDoc.name() + Util.methodDescriptorOf(methodDoc);
    methodHash = computeMethodHash();
}
 
Example 8
Source File: FunctionDBTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetRegisterVariable() throws Exception {
	Function f = createFunction("foo", addr(100), new AddressSet(addr(100), addr(200)));

	DataType[] dt =
		new DataType[] { new ByteDataType(), new WordDataType(), new Pointer16DataType() };

	Register[] regs =
		new Register[] { functionManager.getProgram().getProgramContext().getRegister("r1"),
			functionManager.getProgram().getProgramContext().getRegister("r1"),
			functionManager.getProgram().getProgramContext().getRegister("r3") };

	LocalVariableImpl regVar = new LocalVariableImpl("TestReg0", 0, dt[0], regs[0], program);
	regVar.setComment("My Comment0");
	assertTrue(f.addLocalVariable(regVar, SourceType.USER_DEFINED) instanceof LocalVariableDB);
	regVar = new LocalVariableImpl("TestReg1", 4, dt[1], regs[1], program);
	regVar.setComment("My Comment1");
	assertTrue(f.addLocalVariable(regVar, SourceType.USER_DEFINED) instanceof LocalVariableDB);
	regVar = new LocalVariableImpl("TestReg2", 8, dt[2], regs[2], program);
	regVar.setComment("My Comment2");
	assertTrue(f.addLocalVariable(regVar, SourceType.USER_DEFINED) instanceof LocalVariableDB);

	functionManager.invalidateCache(false);
	f = functionManager.getFunctionAt(addr(100));
	Variable[] vars = f.getLocalVariables();
	assertEquals(3, vars.length);
	Arrays.sort(vars);
	for (int i = 0; i < 3; i++) {
		Variable var = vars[i];
		assertTrue(var.isRegisterVariable());
		assertEquals("TestReg" + i, var.getName());
		assertEquals(i * 4, var.getFirstUseOffset());
		assertEquals("My Comment" + i, var.getComment());
		assertEquals(f, var.getFunction());
		assertEquals(regs[i], var.getRegister());
		assertTrue(dt[i].isEquivalent(var.getDataType()));
	}
}
 
Example 9
Source File: SerialVersionUIDAdder.java    From awacs with Apache License 2.0 5 votes vote down vote up
/**
 * Sorts the items in the collection and writes it to the data output stream
 * 
 * @param itemCollection
 *            collection of items
 * @param dos
 *            a <code>DataOutputStream</code> value
 * @param dotted
 *            a <code>boolean</code> value
 * @exception IOException
 *                if an error occurs
 */
private static void writeItems(final Collection<Item> itemCollection,
        final DataOutput dos, final boolean dotted) throws IOException {
    int size = itemCollection.size();
    Item[] items = itemCollection.toArray(new Item[size]);
    Arrays.sort(items);
    for (int i = 0; i < size; i++) {
        dos.writeUTF(items[i].name);
        dos.writeInt(items[i].access);
        dos.writeUTF(dotted ? items[i].desc.replace('/', '.')
                : items[i].desc);
    }
}
 
Example 10
Source File: ThreeSum2.java    From Algorithms-Fourth-Edition-Exercises with Apache License 2.0 5 votes vote down vote up
public static int count(int[] a) {
    //计算和为0的三元组的数目
    Arrays.sort(a);
    int N = a.length;
    int cnt = 0;
    for (int i = 0; i < N; i++)
        for (int j = i + 1; j < N; j++)
            if (BinarySearch.rank(-a[i] - a[j], a) > j)
                cnt++;
    return cnt;
}
 
Example 11
Source File: DataTransferer.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Helper function to convert a Set of DataFlavors to a sorted array.
 * The array will be sorted according to <code>DataFlavorComparator</code>.
 */
public static DataFlavor[] setToSortedDataFlavorArray(Set flavorsSet) {
    DataFlavor[] flavors = new DataFlavor[flavorsSet.size()];
    flavorsSet.toArray(flavors);
    final Comparator comparator =
            new DataFlavorComparator(IndexedComparator.SELECT_WORST);
    Arrays.sort(flavors, comparator);
    return flavors;
}
 
Example 12
Source File: GridMixRunner.java    From RDFS with Apache License 2.0 5 votes vote down vote up
SimpleStats(long[] data) {
  Arrays.sort(data);
  n = data.length;
  minValue = data[0];
  maxValue = data[n - 1];
  mediumValue = data[n / 2];
  long total = 0;
  for (int i = 0; i < n; i++) {
    total += data[i];
  }
  averageValue = total / n;
}
 
Example 13
Source File: WebsiteRestController.java    From JiwhizBlogWeb with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_TAG_CLOUDS)
public HttpEntity<TagCloud[]> getTagCloud() {
    Map<String, Integer> tagMap = new HashMap<String, Integer>();
    List<BlogPost> blogList = blogPostRepository.findAllPublishedPostsIncludeTags();
    for (BlogPost blog : blogList) {
        for (String tag : blog.getTags()) {
            tag = tag.trim();
            if (tagMap.containsKey(tag)){
                tagMap.put(tag,  tagMap.get(tag) + 1);
            } else {
                tagMap.put(tag,  1);
            }
        }
    }
    
    TagCloud[] tagClouds = new TagCloud[tagMap.size()];
    int index = 0;
    for (String key : tagMap.keySet()) {
        tagClouds[index++] = new TagCloud(key, tagMap.get(key));
    }
    
    Arrays.sort(tagClouds, TagCloud.TagCloudCountComparator);
    
    //get at most first 30 tags
    final int MAX_NUM = 30;
    int returnTagNumber = (tagMap.size() > MAX_NUM) ? MAX_NUM : tagMap.size();
    TagCloud[] returnTagClouds = new TagCloud[returnTagNumber];
    for (int i=0; i<returnTagNumber; i++) {
        returnTagClouds[i] = tagClouds[i];
    }
    Arrays.sort(returnTagClouds, TagCloud.TagCloudNameComparator);
    
    return new ResponseEntity<TagCloud[]>(returnTagClouds, HttpStatus.OK);
}
 
Example 14
Source File: PropertyLimitChecker.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * default constructor.
 */
public PropertyLimitChecker() {
    this.maxPropertyLimitInEntityType = DcCoreConfig.getMaxPropertyCountInEntityType();
    this.simplePropertyLimits = DcCoreConfig.getUserdataSimpleTypePropertyLimits();
    this.complexPropertyLimits = DcCoreConfig.getUserdataComplexTypePropertyLimits();
    this.maxDepth = simplePropertyLimits.length;

    int[] maxPropLimitCopy = Arrays.copyOf(simplePropertyLimits, simplePropertyLimits.length);
    Arrays.sort(maxPropLimitCopy);
    this.simpleMaxForOverAllLayers = maxPropLimitCopy[maxPropLimitCopy.length - 1];
    maxPropLimitCopy = Arrays.copyOf(complexPropertyLimits, complexPropertyLimits.length);
    Arrays.sort(maxPropLimitCopy);
    this.complexMaxForOverallLayers = maxPropLimitCopy[maxPropLimitCopy.length - 1];
}
 
Example 15
Source File: AuthSignature.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * Signature生成(アクセストークン発行リクエストを送信するときに添付するSignatureを生成する).
 * 
 * @param clientId クライアントID
 * @param grantType グラントタイプ
 * @param serviceId サービスID(UIアプリのときはnullまたは""を指定する)
 * @param scopes スコープ
 * @param clientSecret クライアントシークレット
 * @return Signature
 */
public static String generateSignature(final String clientId,
        final String grantType, final String serviceId, final String[] scopes, final String clientSecret) {

    AuthSignature authSignature = new AuthSignature(AuthSignature.SignatureKind.SHA512);
    
    authSignature.empty();
    authSignature.put("clientId", clientId);
    authSignature.put("grantType", grantType);
    if (serviceId != null && serviceId.length() > 0) {
        authSignature.put("serviceId", serviceId);
    }
    
    String strScopes = "";
    Arrays.sort(scopes);
    for (int i = 0; i < scopes.length; i++) {
        String scope = scopes[i];
        if (i > 0) {
            strScopes += ",";
        }
        strScopes += scope;
    }
    authSignature.put("scopes", strScopes);
    
    String signature = authSignature.generateSignature(clientSecret);
    return signature;
}
 
Example 16
Source File: Sorting.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static void checkRange(long[] a, int m) {
    try {
        Arrays.sort(a, m + 1, m);

        failed("Sort does not throw IllegalArgumentException " +
            " as expected: fromIndex = " + (m + 1) +
            " toIndex = " + m);
    }
    catch (IllegalArgumentException iae) {
        try {
            Arrays.sort(a, -m, a.length);

            failed("Sort does not throw ArrayIndexOutOfBoundsException " +
                " as expected: fromIndex = " + (-m));
        }
        catch (ArrayIndexOutOfBoundsException aoe) {
            try {
                Arrays.sort(a, 0, a.length + m);

                failed("Sort does not throw ArrayIndexOutOfBoundsException " +
                    " as expected: toIndex = " + (a.length + m));
            }
            catch (ArrayIndexOutOfBoundsException aie) {
                return;
            }
        }
    }
}
 
Example 17
Source File: CompileJavaPackages.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Split up the sources into compile chunks. If old package dependents information
 * is available, sort the order of the chunks into the most dependent first!
 * (Typically that chunk contains the java.lang package.) In the future
 * we could perhaps improve the heuristics to put the sources into even more sensible chunks.
 * Now the package are simple sorted in alphabetical order and chunked, then the chunks
 * are sorted on how dependent they are.
 *
 * @param pkgSrcs The sources to compile.
 * @param oldPackageDependents Old package dependents, if non-empty, used to sort the chunks.
 * @param numCompiles The number of chunks.
 * @param sourcesPerCompile The number of sources per chunk.
 * @return
 */
CompileChunk[] createCompileChunks(Map<String,Set<URI>> pkgSrcs,
                                   Map<String,Set<String>> oldPackageDependents,
                                   int numCompiles,
                                   int sourcesPerCompile) {

    CompileChunk[] compileChunks = new CompileChunk[numCompiles];
    for (int i=0; i<compileChunks.length; ++i) {
        compileChunks[i] = new CompileChunk();
    }

    // Now go through the packages and spread out the source on the different chunks.
    int ci = 0;
    // Sort the packages
    String[] packageNames = pkgSrcs.keySet().toArray(new String[0]);
    Arrays.sort(packageNames);
    String from = null;
    for (String pkgName : packageNames) {
        CompileChunk cc = compileChunks[ci];
        Set<URI> s = pkgSrcs.get(pkgName);
        if (cc.srcs.size()+s.size() > sourcesPerCompile && ci < numCompiles-1) {
            from = null;
            ci++;
            cc = compileChunks[ci];
        }
        cc.numPackages++;
        cc.srcs.addAll(s);

        // Calculate nice package names to use as information when compiling.
        String justPkgName = Util.justPackageName(pkgName);
        // Fetch how many packages depend on this package from the old build state.
        Set<String> ss = oldPackageDependents.get(pkgName);
        if (ss != null) {
            // Accumulate this information onto this chunk.
            cc.numDependents += ss.size();
        }
        if (from == null || from.trim().equals("")) from = justPkgName;
        cc.pkgNames.append(justPkgName+"("+s.size()+") ");
        cc.pkgFromTos = from+" to "+justPkgName;
    }
    // If we are compiling serially, sort the chunks, so that the chunk (with the most dependents) (usually the chunk
    // containing java.lang.Object, is to be compiled first!
    // For concurrent compilation, this does not matter.
    Arrays.sort(compileChunks);
    return compileChunks;
}
 
Example 18
Source File: MVELEnabledBuilder.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public void build(RuleBuildContext context) {
    // pushing consequence LHS into the stack for variable resolution
    context.getDeclarationResolver().pushOnBuildStack( context.getRule().getLhs() );

    try {
        // This builder is re-usable in other dialects, so specify by name            
        MVELDialect dialect = (MVELDialect) context.getDialect( "mvel" );

        Map<String, Class< ? >> otherVars = new HashMap<String, Class< ? >>();
        otherVars.put( "rule",
                       RuleImpl.class );

        Map<String, Declaration> declrs = context.getDeclarationResolver().getDeclarations( context.getRule() );

        AnalysisResult analysis = dialect.analyzeExpression( context,
                                                             context.getRuleDescr(),
                                                             context.getRuleDescr().getEnabled(),
                                                             new BoundIdentifiers( DeclarationScopeResolver.getDeclarationClasses( declrs ),
                                                                                   context ),
                                                             otherVars );

        final BoundIdentifiers usedIdentifiers = analysis.getBoundIdentifiers();
        int i = usedIdentifiers.getDeclrClasses().keySet().size();
        Declaration[] previousDeclarations = new Declaration[i];
        i = 0;
        for ( String id :  usedIdentifiers.getDeclrClasses().keySet() ) {
            previousDeclarations[i++] = declrs.get( id );
        }
        Arrays.sort( previousDeclarations, SortDeclarations.instance  );            

        String exprStr = context.getRuleDescr().getEnabled();
        exprStr = exprStr.substring( 1,
                                     exprStr.length() - 1 ) + " ";
        MVELCompilationUnit unit = dialect.getMVELCompilationUnit( exprStr,
                                                                   analysis,
                                                                   previousDeclarations,
                                                                   null,
                                                                   otherVars,
                                                                   context,
                                                                   "drools",
                                                                   KnowledgeHelper.class,
                                                                   false,
                                                                   MVELCompilationUnit.Scope.EXPRESSION );

        MVELEnabledExpression expr = new MVELEnabledExpression( unit,
                                                                dialect.getId() );
        context.getRule().setEnabled( KiePolicyHelper.isPolicyEnabled() ? new SafeEnabled(expr) : expr );

        MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData( "mvel" );
        data.addCompileable( context.getRule(),
                             expr );

        expr.compile( data, context.getRule() );
    } catch ( final Exception e ) {
        DialectUtil.copyErrorLocation(e, context.getRuleDescr());
        context.addError( new DescrBuildError( context.getParentDescr(),
                                                      context.getRuleDescr(),
                                                      null,
                                                      "Unable to build expression for 'enabled' : " + e.getMessage() + " '" + context.getRuleDescr().getEnabled() + "'" ) );
    }
}
 
Example 19
Source File: Arja_00159_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Find the realEigenvalues.
 * @exception InvalidMatrixException if a block cannot be diagonalized
 */
private void findEigenvalues()
    throws InvalidMatrixException {

    // compute splitting points
    List<Integer> splitIndices = computeSplits();

    // find realEigenvalues in each block
    realEigenvalues = new double[main.length];
    imagEigenvalues = new double[main.length];
    int begin = 0;
    for (final int end : splitIndices) {
        final int n = end - begin;
        switch (n) {

        case 1:
            // apply dedicated method for dimension 1
            process1RowBlock(begin);
            break;

        case 2:
            // apply dedicated method for dimension 2
            process2RowsBlock(begin);
            break;

        case 3:
            // apply dedicated method for dimension 3
            process3RowsBlock(begin);
            break;

        default:

            // choose an initial shift for LDL<sup>T</sup> decomposition
            final double[] range       = eigenvaluesRange(begin, n);
            final double oneFourth     = 0.25 * (3 * range[0] + range[1]);
            final int oneFourthCount   = countEigenValues(oneFourth, begin, n);
            final double threeFourth   = 0.25 * (range[0] + 3 * range[1]);
            final int threeFourthCount = countEigenValues(threeFourth, begin, n);
            final boolean chooseLeft   = (oneFourthCount - 1) >= (n - threeFourthCount);
            final double lambda        = chooseLeft ? range[0] : range[1];

            tau = (range[1] - range[0]) * MathUtils.EPSILON * n + 2 * minPivot;

            // decompose T-&lambda;I as LDL<sup>T</sup>
            ldlTDecomposition(lambda, begin, n);

            // apply general dqd/dqds method
            processGeneralBlock(n);

            // extract realEigenvalues
            if (chooseLeft) {
                for (int i = 0; i < n; ++i) {
                    realEigenvalues[begin + i] = lambda + work[4 * i];
                }
            } else {
                for (int i = 0; i < n; ++i) {
                    realEigenvalues[begin + i] = lambda - work[4 * i];
                }
            }

        }
        begin = end;
    }

    // sort the realEigenvalues in decreasing order
    Arrays.sort(realEigenvalues);
    int j = realEigenvalues.length - 1;
    for (int i = 0; i < j; ++i) {
        final double tmp = realEigenvalues[i];
        realEigenvalues[i] = realEigenvalues[j];
        realEigenvalues[j] = tmp;
        --j;
    }

}
 
Example 20
Source File: DetailFragment.java    From kolabnotes-android with GNU Lesser General Public License v3.0 3 votes vote down vote up
Spinner initSpinner(){
    Spinner spinner = (Spinner) activity.findViewById(R.id.spinner_notebook);

    final ActiveAccount activeAccount = activeAccountRepository.getActiveAccount();

    List<Notebook> notebooks = notebookRepository.getAll(activeAccount.getAccount(), activeAccount.getRootFolder());

    String[] notebookArr = new String[notebooks.size()];

    for(int i=0; i<notebooks.size();i++){
        String summary = notebooks.get(i).getSummary();

        if(notebooks.get(i).isShared()){
            summary = ((SharedNotebook)notebooks.get(i)).getShortName();
        }

        notebookArr[i] = summary;
    }

    Arrays.sort(notebookArr);

    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(activity,R.layout.notebook_spinner_item,notebookArr);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    return spinner;
}