Jave Code Examples for 'sort'

60 Jave code examples are found related to "sort". These examples are extracted from open source projects. 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.
Example 1
Project: bistoury   Author: qunarcorp   File: ProfilerDataDumper.java    License: GNU General Public License v3.0 7 votes vote down vote up
private List<Map.Entry<Integer, Long>> sortByValue(Map<Integer, Long> countMap) {
    List<Map.Entry<Integer, Long>> countEntryList = new ArrayList<>(countMap.entrySet());
    Collections.sort(countEntryList, new Comparator<Map.Entry<Integer, Long>>() {
        @Override
        public int compare(Map.Entry<Integer, Long> l, Map.Entry<Integer, Long> r) {
            long left = l.getValue();
            long right = r.getValue();
            if (left > right) {
                return -1;
            } else if (left == right) {
                return 0;
            }
            return 1;
        }
    });
    return countEntryList;
}
 
Example 2
Project: CompetitiveJava   Author: dubesar   File: MergeSortinLinkedList.java    License: MIT License 7 votes vote down vote up
node mergeSort(node h) 
{ 
    if (h == null || h.next == null) { 
        return h; 
    } 
  
    node middle = getMiddle(h); 
    node nextofmiddle = middle.next; 
  
    middle.next = null; 
  
    node left = mergeSort(h); 
  
    node right = mergeSort(nextofmiddle); 
    node sortedlist = sortedMerge(left, right); 
    return sortedlist; 
}
 
Example 3
Project: bisq-core   Author: bisq-network   File: BisqDefaultCoinSelector.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
protected void sortOutputs(ArrayList<TransactionOutput> outputs) {
    Collections.sort(outputs, (a, b) -> {
        int depth1 = a.getParentTransactionDepthInBlocks();
        int depth2 = b.getParentTransactionDepthInBlocks();
        Coin aValue = a.getValue();
        Coin bValue = b.getValue();
        BigInteger aCoinDepth = BigInteger.valueOf(aValue.value).multiply(BigInteger.valueOf(depth1));
        BigInteger bCoinDepth = BigInteger.valueOf(bValue.value).multiply(BigInteger.valueOf(depth2));
        int c1 = bCoinDepth.compareTo(aCoinDepth);
        if (c1 != 0) return c1;
        // The "coin*days" destroyed are equal, sort by value alone to get the lowest transaction size.
        int c2 = bValue.compareTo(aValue);
        if (c2 != 0) return c2;
        // They are entirely equivalent (possibly pending) so sort by hash to ensure a total ordering.
        BigInteger aHash = a.getParentTransactionHash() != null ?
                a.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        BigInteger bHash = b.getParentTransactionHash() != null ?
                b.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        return aHash.compareTo(bHash);
    });
}
 
Example 4
/**
 * Sorts the {@link AbstractAttributeStatisticsModel}s via their attribute names.
 *
 * @param direction
 */
private void sortByName(List<AbstractAttributeStatisticsModel> list, final SortingDirection direction) {
	sort(list, (o1, o2) -> {
		int sortResult = o1.getAttribute().getName().compareTo(o2.getAttribute().getName());
		switch (direction) {
			case ASCENDING:
				return -1 * sortResult;
			case DESCENDING:
				return sortResult;
			case UNDEFINED:
				return 0;
			default:
				return sortResult;
		}
	});
}
 
Example 5
Project: rapidminer-studio   Author: rapidminer   File: ExtendedJTable.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void sortColumnsAccordingToNames() {
	int offset = 0;
	if (fixFirstColumn) {
		offset = 1;
	}
	for (int i = offset; i < getColumnCount(); i++) {
		int minIndex = -1;
		String minName = null;
		for (int j = i; j < getColumnCount(); j++) {
			String currentName = getColumnName(j);
			if (minName == null || currentName.compareTo(minName) < 0) {
				minName = currentName;
				minIndex = j;
			}
		}
		moveColumn(minIndex, i);
	}
}
 
Example 6
/**
 * Sorts a list of attributes alphabetically according to the desired sort direction. CAUTION:
 * The provided list 'unsortedAttributeList' will be changed internally.
 */
private void sortAttributeListAlphabetically(List<Attribute> unsortedAttributeList) throws UndefinedParameterError {

	// sort direction none -> just return
	if (getParameterAsString(PARAMETER_SORT_DIRECTION).equals(DIRECTION_NONE)) {
		return;
	}

	// sort attributes
	Collections.sort(unsortedAttributeList, new Comparator<Attribute>() {

		@Override
		public int compare(Attribute o1, Attribute o2) {
			return Collator.getInstance().compare(o1.getName(), o2.getName());
		}

	});

	// if descending, reverse sort
	if (getParameterAsString(PARAMETER_SORT_DIRECTION).equals(DIRECTION_DESCENDING)) {
		Collections.reverse(unsortedAttributeList);
	}
}
 
Example 7
Project: deeplearning4j   Author: eclipse   File: KerasTokenizer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sort HashMap by values in reverse order
 *
 * @param map input HashMap
 * @return sorted HashMap
 */
private static HashMap reverseSortByValues(HashMap map) {
    List list = new LinkedList(map.entrySet());
    Collections.sort(list, new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((Comparable) ((Map.Entry) (o1)).getValue())
                    .compareTo(((Map.Entry) (o2)).getValue());
        }
    });
    HashMap sortedHashMap = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        sortedHashMap.put(entry.getKey(), entry.getValue());
    }
    return sortedHashMap;
}
 
Example 8
public ActionForward prepareSortBibliography(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {
    ExecutionCourse executionCourse = getExecutionCourse(request);
    boolean optional = request.getParameter("optional") != null;
    List<BibliographicReference> references;

    if (optional) {
        references = getOptionalBibliographicReferences(executionCourse);
    } else {
        references = getMainBibliographicReferences(executionCourse);
    }

    request.setAttribute("references", references);
    request.setAttribute("optional", optional);

    return forward(request, "/teacher/executionCourse/orderBibliographicReferences.jsp");
}
 
Example 9
Project: influxdb-client-java   Author: influxdata   File: SortFluxTest.java    License: MIT License 6 votes vote down vote up
@Test
void sortByParameters() {

    Flux flux = Flux
            .from("telegraf")
            .sort()
            .withPropertyNamed("columns", "columnsParameter")
            .withPropertyNamed("desc", "descParameter");

    HashMap<String, Object> parameters = new HashMap<>();
    parameters.put("columnsParameter", new String[]{"region", "tag"});
    parameters.put("descParameter", false);

    String expected = "from(bucket:\"telegraf\") |> sort(columns: [\"region\", \"tag\"], desc: false)";

    Assertions
            .assertThat(flux.toString(parameters))
            .isEqualToIgnoringWhitespace(expected);
}
 
Example 10
Project: albert   Author: pospospos2007   File: BaseSearchService.java    License: MIT License 6 votes vote down vote up
protected SortBuilder addSort(SearchParam param){
		Integer sort = param.getSort();
		
//		if(null==sort){
//			return SortBuilders.fieldSort("lastRefresh").order(SortOrder.DESC);
//		}else if(Constants.Sort.nearest == sort){
//			return SortBuilders.geoDistanceSort("geoPoint").point(param.getLat(), param.getLon()).order(SortOrder.ASC);
//		
//		} else if(Constants.Sort.pageView == sort){
//			return SortBuilders.fieldSort("reviewNum").order(SortOrder.DESC);
//		
//		} else if(Constants.Sort.score == sort){
//			return SortBuilders.fieldSort("avgScore").order(SortOrder.DESC);
//		
//		} else if(Constants.Sort.priceAsc == sort){
//			return SortBuilders.fieldSort("price").order(SortOrder.ASC);
//		
//		} else if(Constants.Sort.priceDesc == sort){
//			return SortBuilders.fieldSort("price").order(SortOrder.DESC);
//		
//		}
		
		return SortBuilders.fieldSort("addTime").order(SortOrder.DESC);
	}
 
Example 11
Project: albert   Author: pospospos2007   File: SortColors.java    License: MIT License 6 votes vote down vote up
public void sortColors(int[] nums) {
    int left = 0,right = nums.length-1;
    int temp = 0;
    for(int i=0;i<=right;)
        if(nums[i]==1){
            i++;
        }else if(nums[i]==0){
            temp = nums[left];
            nums[left] = nums[i];
            nums[i] = temp;
            left++;
            i++;

        }else{
            temp = nums[right];
            nums[right] = nums[i];
            nums[i] = temp;
            right--;
        }
}
 
Example 12
Project: Nimingban   Author: seven332   File: SortForumsActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onBindViewHolder(ForumHolder holder, int position) {
    if (position > 0) {
        ACForumRaw raw = mLazyList.get(position - 1);
        holder.visibility.setActivated(raw.getVisibility());
        if (mAutoSorting) {
            holder.dragHandler.setVisibility(View.GONE);
            holder.pinning.setVisibility(View.VISIBLE);
            holder.pinning.setActivated(ForumAutoSortingUtils.isACForumPinned(raw));
        } else {
            holder.pinning.setVisibility(View.GONE);
            holder.dragHandler.setVisibility(View.VISIBLE);
        }

        CharSequence name = mForumNames.get(position);
        if (name == null) {
            if (raw.getDisplayname() == null) {
                name = "Forum";
            } else {
                name = Html.fromHtml(raw.getDisplayname());
            }
            mForumNames.put(position, name);
        }
        holder.forum.setText(name);
    }
}
 
Example 13
Project: Nimingban   Author: seven332   File: SortForumsActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void showStarGuide() {
    new GuideHelper.Builder(this)
            .setColor(ResourcesUtils.getAttrColor(this, R.attr.colorPrimary))
            .setPadding(LayoutUtils.dp2pix(this, 16))
            .setPaddingTop(LayoutUtils.dp2pix(this, 56))
            .setPaddingBottom(LayoutUtils.dp2pix(this, 56))
            .setMessagePosition(Gravity.RIGHT)
            .setMessage(getString(R.string.click_star_icon_pin))
            .setButton(getString(R.string.get_it))
            .setBackgroundColor(0x73000000)
            .setOnDissmisListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Settings.putGuidePinningStar(false);
                }
            }).show();
}
 
Example 14
Project: Nimingban   Author: seven332   File: SortForumsActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (autoSortingSwitch == buttonView) {
        mAutoSorting = isChecked;
        Settings.putForumAutoSorting(isChecked);

        // update the list to sort them according to the present setting
        updateLazyList(false);
        // the list could be dramatically different so update them all
        mAdapter.notifyDataSetChanged();

        // show guide
        tryShowSecondGuide();

        mNeedUpdate = true;
    }
}
 
Example 15
Project: hollow   Author: Netflix   File: HollowCombiner.java    License: Apache License 2.0 6 votes vote down vote up
private List<PrimaryKey> sortPrimaryKeys(List<PrimaryKey> primaryKeys) {
    final List<HollowSchema> dependencyOrderedSchemas = HollowSchemaSorter.dependencyOrderedSchemaList(output.getSchemas());
    primaryKeys.sort(new Comparator<PrimaryKey>() {
        public int compare(PrimaryKey o1, PrimaryKey o2) {
            return schemaDependencyIdx(o1) - schemaDependencyIdx(o2);
        }

        private int schemaDependencyIdx(PrimaryKey key) {
            for (int i = 0; i < dependencyOrderedSchemas.size(); i++) {
                if (dependencyOrderedSchemas.get(i).getName().equals(key.getType()))
                    return i;
            }
            throw new IllegalArgumentException("Primary key defined for non-existent type: " + key.getType());
        }
    });
    
    return primaryKeys;
}
 
Example 16
Project: smithy   Author: awslabs   File: Node.java    License: Apache License 2.0 6 votes vote down vote up
private static Node sortNode(Node node, Comparator<StringNode> keyComparator) {
    return node.accept(new NodeVisitor.Default<Node>() {
        @Override
        protected Node getDefault(Node node) {
            return node;
        }

        @Override
        public Node objectNode(ObjectNode node) {
            Map<StringNode, Node> members = new TreeMap<>(keyComparator);
            node.getMembers().forEach((k, v) -> members.put(k, sortNode(v, keyComparator)));
            return new ObjectNode(members, node.getSourceLocation());
        }

        @Override
        public Node arrayNode(ArrayNode node) {
            return node.getElements().stream()
                    .map(element -> sortNode(element, keyComparator))
                    .collect(ArrayNode.collect(node.getSourceLocation()));
        }
    });
}
 
Example 17
Project: bisq   Author: bisq-network   File: BisqDefaultCoinSelector.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
protected void sortOutputs(ArrayList<TransactionOutput> outputs) {
    Collections.sort(outputs, (a, b) -> {
        int depth1 = a.getParentTransactionDepthInBlocks();
        int depth2 = b.getParentTransactionDepthInBlocks();
        Coin aValue = a.getValue();
        Coin bValue = b.getValue();
        BigInteger aCoinDepth = BigInteger.valueOf(aValue.value).multiply(BigInteger.valueOf(depth1));
        BigInteger bCoinDepth = BigInteger.valueOf(bValue.value).multiply(BigInteger.valueOf(depth2));
        int c1 = bCoinDepth.compareTo(aCoinDepth);
        if (c1 != 0) return c1;
        // The "coin*days" destroyed are equal, sort by value alone to get the lowest transaction size.
        int c2 = bValue.compareTo(aValue);
        if (c2 != 0) return c2;
        // They are entirely equivalent (possibly pending) so sort by hash to ensure a total ordering.
        BigInteger aHash = a.getParentTransactionHash() != null ?
                a.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        BigInteger bHash = b.getParentTransactionHash() != null ?
                b.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        return aHash.compareTo(bHash);
    });
}
 
Example 18
Project: ccu-historian   Author: mdzio   File: DefaultKeyedValues.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sorts the items in the list by key.
 *
 * @param order  the sort order (<code>null</code> not permitted).
 */
public void sortByKeys(SortOrder order) {
    final int size = this.keys.size();
    final DefaultKeyedValue[] data = new DefaultKeyedValue[size];

    for (int i = 0; i < size; i++) {
        data[i] = new DefaultKeyedValue((Comparable) this.keys.get(i),
                (Number) this.values.get(i));
    }

    Comparator comparator = new KeyedValueComparator(
            KeyedValueComparatorType.BY_KEY, order);
    Arrays.sort(data, comparator);
    clear();

    for (int i = 0; i < data.length; i++) {
        final DefaultKeyedValue value = data[i];
        addValue(value.getKey(), value.getValue());
    }
}
 
Example 19
Project: Tomcat8-Source-Read   Author: chenmudu   File: DefaultServlet.java    License: MIT License 6 votes vote down vote up
public SortManager(boolean directoriesFirst) {
    resourceNameComparator = new ResourceNameComparator();
    resourceNameComparatorAsc = Collections.reverseOrder(resourceNameComparator);
    resourceSizeComparator = new ResourceSizeComparator(resourceNameComparator);
    resourceSizeComparatorAsc = Collections.reverseOrder(resourceSizeComparator);
    resourceLastModifiedComparator = new ResourceLastModifiedDateComparator(resourceNameComparator);
    resourceLastModifiedComparatorAsc = Collections.reverseOrder(resourceLastModifiedComparator);

    if(directoriesFirst) {
        resourceNameComparator = new DirsFirstComparator(resourceNameComparator);
        resourceNameComparatorAsc = new DirsFirstComparator(resourceNameComparatorAsc);
        resourceSizeComparator = new DirsFirstComparator(resourceSizeComparator);
        resourceSizeComparatorAsc = new DirsFirstComparator(resourceSizeComparatorAsc);
        resourceLastModifiedComparator = new DirsFirstComparator(resourceLastModifiedComparator);
        resourceLastModifiedComparatorAsc = new DirsFirstComparator(resourceLastModifiedComparatorAsc);
    }

    defaultResourceComparator = resourceNameComparator;
}
 
Example 20
Project: Neural-Network-Programming-with-Java-SecondEdition   Author: PacktPublishing   File: DataSet.java    License: MIT License 6 votes vote down vote up
public void sortBy(int col){
    double[] value = this.getData(col);
    double[] ordered = ArrayOperations.quickSort(value);
    int[] ordIndexes = ArrayOperations.getIndexes(value, ordered);
    ArrayList<ArrayList<Double>> newData = new ArrayList<>();
    for(int i=0;i<numberOfRecords;i++){
        ArrayList<Double> newLine = new ArrayList<>();            
        for(int j=0;j<numberOfColumns;j++){
            double v = data.get(ordIndexes[i]).get(j);
            newLine.add(v);
        }
        newData.add(newLine);
    }
    this.data=newData;

}
 
Example 21
Project: bamboobsc   Author: billchen198318   File: PageOf.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 把要代入查grid的 hql 的 map 參數加上 order by 條件
 * orderBy		如 kpi.id, kpi.name
 * sortType		如 ASC 或 DESC
 * @param queryParam
 */
public Map<String, Object> setQueryOrderSortParameter(Map<String, Object> queryParam) {
	if (queryParam == null) {
		return queryParam;
	}
	if (queryParam.get(Constants._RESERVED_PARAM_NAME_QUERY_ORDER_BY) == null) {
		if (!StringUtils.isBlank(this.getOrderBy())) {
			queryParam.put(Constants._RESERVED_PARAM_NAME_QUERY_ORDER_BY, this.getOrderBy());
		}
	}
	if (queryParam.get(Constants._RESERVED_PARAM_NAME_QUERY_SORT_TYPE) == null) {
		if (!StringUtils.isBlank(this.getSortType())) {
			queryParam.put(Constants._RESERVED_PARAM_NAME_QUERY_SORT_TYPE, this.getSortType());
		}
	}
	return queryParam;
}
 
Example 22
Project: FuzzDroid   Author: srasthofer   File: MapUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(
		Map<K, V> map) {
	List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(
			map.entrySet());
	Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
		public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
			return -(o1.getValue()).compareTo(o2.getValue());
		}
	});

	Map<K, V> result = new LinkedHashMap<K, V>();
	for (Map.Entry<K, V> entry : list) {
		result.put(entry.getKey(), entry.getValue());
	}
	return result;
}
 
Example 23
Project: sax-vsm_classic   Author: jMotif   File: SAXVSMDirectSampler.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * returns sorted array and the original indicies
 * 
 * @param array
 * @return
 */
private static double[][] sort(double[] array) {
  double[][] arr1 = new double[3][array.length];
  double[][] arr2 = new double[2][array.length];
  System.arraycopy(array, 0, arr1[0], 0, array.length);
  Arrays.sort(array);
  for (int i = 0; i < array.length; i++) {
    for (int i1 = 0; i1 < array.length; i1++) {
      if (array[i] == arr1[0][i1] && arr1[2][i1] != 1) {
        arr1[2][i1] = 1;
        arr1[1][i] = i1;
        break;
      }
    }
  }
  arr2[0] = array;
  arr2[1] = arr1[1];
  return arr2;
}
 
Example 24
Project: gcs   Author: richardwilkes   File: QuickSort.java    License: Mozilla Public License 2.0 6 votes vote down vote up
private static <T> void quicksort(List<T> list, Comparator<T> cmp)
{
    Deque<Integer> stack = new ArrayDeque<Integer>();
    stack.push(0);
    stack.push(list.size());
    while (!stack.isEmpty())
    {
        int right = stack.pop();
        int left = stack.pop();
        if (right - left < 2)
        {
            continue;
        }
        int p = left + ((right - left) / 2);
        p = partition(list, cmp, p, left, right);

        stack.push(p + 1);
        stack.push(right);

        stack.push(left);
        stack.push(p);
    }
}
 
Example 25
Project: gcs   Author: richardwilkes   File: PdfCollectionSort.java    License: Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Defines the sort order of the field (ascending or descending).
 * @param ascending	an array with every element corresponding with a name of a field.
 */
public void setSortOrder(boolean[] ascending) {
	PdfObject o = get(PdfName.S);
	if (o instanceof PdfArray) {
		if (((PdfArray)o).size() != ascending.length) {
			throw new IllegalArgumentException("The number of booleans in this array doesn't correspond with the number of fields.");
		}
		PdfArray array = new PdfArray();
		for (int i = 0; i < ascending.length; i++) {
			array.add(new PdfBoolean(ascending[i]));
		}
		put(PdfName.A, array);
	}
	else {
		throw new IllegalArgumentException("You need a single boolean for this collection sort dictionary.");
	}
}
 
Example 26
Project: tracingplane-java   Author: tracingplane   File: TestSort.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSimpleSort() {
    ByteBuffer payloadA = ByteBuffer.allocate(4);
    payloadA.putInt(0, 100);

    ByteBuffer payloadB = ByteBuffer.allocate(4);
    payloadB.putInt(0, 55);
    
    BaggageWriter writer = BaggageWriter.create();
    writer.writeBytes(payloadA);
    writer.writeBytes(payloadB);
    writer.sortData();
    
    List<ByteBuffer> atoms = writer.atoms();
    
    BaggageReader reader = BaggageReader.create(atoms);
    ByteBuffer firstRead = reader.nextData();
    ByteBuffer secondRead = reader.nextData();
    
    assertEquals(payloadB, firstRead);
    assertEquals(payloadA, secondRead);
}
 
Example 27
Project: tracingplane-java   Author: tracingplane   File: TestSort.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testMultiSort() {
    int numbufs = 100;
    ByteBuffer[] bufs = new ByteBuffer[numbufs];
    for (int i = 0; i < numbufs; i++) {
        bufs[i] = ByteBuffer.allocate(4);
        bufs[i].putInt(0, numbufs-i-1);
    }
    
    BaggageWriter writer = BaggageWriter.create();
    for (int i = 0; i < numbufs; i++) {
        writer.writeBytes(bufs[i]);
    }
    writer.sortData();
    
    List<ByteBuffer> atoms = writer.atoms();
    
    BaggageReader reader = BaggageReader.create(atoms);
    for (int i = 0; i < numbufs; i++) {
        ByteBuffer bufRead = reader.nextData();
        assertEquals(bufs[numbufs-i-1], bufRead);
    }
}
 
Example 28
Project: tilesfx   Author: HanSolo   File: LeaderBoardTileSkin.java    License: Apache License 2.0 6 votes vote down vote up
private void sortItems() {
    List<LeaderBoardItem> items = tile.getLeaderBoardItems();
    switch(tile.getItemSorting()) {
        case ASCENDING :
            switch(tile.getItemSortingTopic()) {
                case TIMESTAMP: items.sort(Comparator.comparing(LeaderBoardItem::getTimestamp)); break;
                case DURATION : items.sort(Comparator.comparing(LeaderBoardItem::getDuration)); break;
                case VALUE    :
                default       : items.sort(Comparator.comparing(LeaderBoardItem::getValue)); break;
            }
            break;
        case DESCENDING:
            switch(tile.getItemSortingTopic()) {
                case TIMESTAMP: items.sort(Comparator.comparing(LeaderBoardItem::getTimestamp).reversed()); break;
                case DURATION : items.sort(Comparator.comparing(LeaderBoardItem::getDuration).reversed()); break;
                case VALUE    :
                default       : items.sort(Comparator.comparing(LeaderBoardItem::getValue).reversed()); break;
            }
            break;
        case NONE:
        default: break;
    }
    items.forEach(i -> i.setIndex(items.indexOf(i)));
    updateChart();
}
 
Example 29
Project: nexus-public   Author: sonatype   File: SearchUtils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private SortOrder getValidSortOrder(String direction, SortOrder defaultValue) {
  if (direction != null) {
    switch (direction.toLowerCase()) {
      case "asc":
      case "ascending":
        return SortOrder.ASC;
      case "desc":
      case "descending":
        return SortOrder.DESC;
      default:
        break;
    }
  }

  return defaultValue;
}
 
Example 30
Project: nexus-public   Author: sonatype   File: SearchUtils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public List<SortBuilder> getSortBuilders(final String sort, final String direction, boolean allowAnySort) {
  if (sort == null) {
    return emptyList();
  }

  switch (sort) {
    case GROUP:
      return handleGroupSort(direction);
    case NAME:
      return handleNameSort(direction);
    case VERSION:
      return handleVersionSort(direction);
    case "repository":
    case "repositoryName":
      return handleRepositoryNameSort(direction);
    default:
      return handleOtherSort(sort, direction, allowAnySort);
  }
}
 
Example 31
Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: Util.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private static void quickSort(char[][] list, int left, int right) {
	int original_left= left;
	int original_right= right;
	char[] mid= list[left + (right - left) / 2];
	do {
		while (compare(list[left], mid) < 0) {
			left++;
		}
		while (compare(mid, list[right]) < 0) {
			right--;
		}
		if (left <= right) {
			char[] tmp= list[left];
			list[left]= list[right];
			list[right]= tmp;
			left++;
			right--;
		}
	} while (left <= right);
	if (original_left < right) {
		quickSort(list, original_left, right);
	}
	if (left < original_right) {
		quickSort(list, left, original_right);
	}
}
 
Example 32
/**
 * Calculates the required text edits to sort the <code>unit</code>
 * @param group
 * @return the edit or null if no sorting is required
 */
public TextEdit calculateEdit(org.eclipse.jdt.core.dom.CompilationUnit unit, TextEditGroup group) throws JavaModelException {
	if (this.elementsToProcess.length != 1)
		throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS));

	if (!(this.elementsToProcess[0] instanceof ICompilationUnit))
		throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this.elementsToProcess[0]));

	try {
		beginTask(Messages.operation_sortelements, getMainAmountOfWork());

		ICompilationUnit cu= (ICompilationUnit)this.elementsToProcess[0];
		String content= cu.getBuffer().getContents();
		ASTRewrite rewrite= sortCompilationUnit(unit, group);
		if (rewrite == null) {
			return null;
		}

		Document document= new Document(content);
		return rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true));
	} finally {
		done();
	}
}
 
Example 33
Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: Util.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static void reverseQuickSort(char[][] list, int left, int right) {
	int original_left= left;
	int original_right= right;
	char[] mid= list[left + ((right-left)/2)];
	do {
		while (CharOperation.compareTo(list[left], mid) > 0) {
			left++;
		}
		while (CharOperation.compareTo(mid, list[right]) > 0) {
			right--;
		}
		if (left <= right) {
			char[] tmp= list[left];
			list[left]= list[right];
			list[right]= tmp;
			left++;
			right--;
		}
	} while (left <= right);
	if (original_left < right) {
		reverseQuickSort(list, original_left, right);
	}
	if (left < original_right) {
		reverseQuickSort(list, left, original_right);
	}
}
 
Example 34
private int sortParticipants(ArrayList group, IConfigurationElement[] configElements, int index) {
	int size = group.size();
	if (size == 0) return index;
	Object[] elements = group.toArray();
	Util.sort(elements, new Util.Comparer() {
		public int compare(Object a, Object b) {
			if (a == b) return 0;
			String id = ((IConfigurationElement) a).getAttribute("id"); //$NON-NLS-1$
			if (id == null) return -1;
			IConfigurationElement[] requiredElements = ((IConfigurationElement) b).getChildren("requires"); //$NON-NLS-1$
			for (int i = 0, length = requiredElements.length; i < length; i++) {
				IConfigurationElement required = requiredElements[i];
				if (id.equals(required.getAttribute("id"))) //$NON-NLS-1$
					return 1;
			}
			return -1;
		}
	});
	for (int i = 0; i < size; i++)
		configElements[index+i] = (IConfigurationElement) elements[i];
	return index + size;
}
 
Example 35
public void sortIn(ImportDeclEntry imp) {
	String fullImportName= imp.getElementName();
	int insertPosition= -1;
	int nInports= this.importEntries.size();
	for (int i= 0; i < nInports; i++) {
		ImportDeclEntry curr= getImportAt(i);
		if (!curr.isComment()) {
			int cmp= curr.compareTo(fullImportName, imp.isStatic());
			if (cmp == 0) {
				return; // exists already
			} else if (cmp > 0 && insertPosition == -1) {
				insertPosition= i;
			}
		}
	}
	if (insertPosition == -1) {
		this.importEntries.add(imp);
	} else {
		this.importEntries.add(insertPosition, imp);
	}
}
 
Example 36
/**
 * {@inheritDoc}
 */
@Override
protected ICleanUp[] getCleanUps(ICompilationUnit[] units) {
	try {
        if (!hasMembersToSort(units)) {
			MessageDialog.openInformation(getShell(), ActionMessages.MultiSortMembersAction_noElementsToSortDialog_title, ActionMessages.MultiSortMembersAction_noElementsToSortDialog_message);
        	return null;
        }
       } catch (JavaModelException e) {
       	JavaPlugin.log(e);
        return null;
       }

	Map<String, String> settings= getSettings();
	if (settings == null)
		return null;

	return new ICleanUp[] {
		new SortMembersCleanUp(settings)
	};
}
 
Example 37
Project: development   Author: servicecatalog   File: RichLazyDataModel.java    License: Apache License 2.0 6 votes vote down vote up
public void toggleSort() {
    for (Map.Entry<String, org.richfaces.component.SortOrder> entry : sortOrders
            .entrySet()) {
        org.richfaces.component.SortOrder newOrder;

        if (entry.getKey().equals(sortProperty)) {
            if (entry.getValue() == org.richfaces.component.SortOrder.ascending) {
                newOrder = org.richfaces.component.SortOrder.descending;
            } else {
                newOrder = org.richfaces.component.SortOrder.ascending;
            }
        } else {
            newOrder = org.richfaces.component.SortOrder.unsorted;
        }

        entry.setValue(newOrder);
    }
}
 
Example 38
Project: development   Author: servicecatalog   File: CategorySelectionBeanTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void sortCategories() {
    // given
    givenUnsortedCategories();

    // when
    categorySelectionBean.sortCategories();

    // then
    List<VOCategory> categories = categorySelectionBean.categoriesForMarketplace;
    assertEquals("%", categories.get(0).getName());
    assertEquals("&", categories.get(1).getName());
    assertEquals("A", categories.get(2).getName());
    assertEquals("a", categories.get(3).getName());
    assertEquals("Aa", categories.get(4).getName());
    assertEquals("aA", categories.get(5).getName());
    assertEquals("B", categories.get(6).getName());
    assertEquals("b", categories.get(7).getName());
}
 
Example 39
Project: development   Author: servicecatalog   File: SubscriptionDaoIT_Paging_Sorting_Supplier.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getSubscriptionsForMyCustomersAscendingSortByActivationTime()
        throws Exception {
    // given
    final Sorting sorting = new Sorting(TableColumns.ACTIVATION_TIME,
            SortOrder.ASC);
    Set<Filter> filterSet = createFilterSet(null, null,
            SUPPLIER_CUSTOMER_FOR_ACTTIME, null, null);
    final Pagination pagination = createPagination(0,
            NUM_CUSTOMER_SUBSCRIPTIONS, sorting, filterSet);

    // when
    List<Subscription> result = runTX(new Callable<List<Subscription>>() {
        @Override
        public List<Subscription> call() throws Exception {
            return dao.getSubscriptionsForMyCustomers(supplierUser, states,
                    pagination);
        }
    });

    // then
    assertEquals(NUM_ACTIVATION_TIMES, result.size());
    for (int i = 0; i < result.size(); i++)
        assertEquals(SUBSCRIPTION_ID_FOR_ACTIVATION_TIME_CASE + i,
                result.get(i).getSubscriptionId());
}
 
Example 40
Project: development   Author: servicecatalog   File: SubscriptionDaoIT_Paging_Sorting_Supplier.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getSubscriptionsForMyCustomersAscendingSortBySubscriptionId()
        throws Exception {
    // given
    final Sorting sorting = new Sorting(TableColumns.SUBSCRIPTION_ID,
            SortOrder.ASC);
    Set<Filter> filterSet = createFilterSet(null, null,
            SUPPLIER_CUSTOMER_FOR_SUB_ID_SORTING, null, null);
    final Pagination pagination = createPagination(0,
            NUM_CUSTOMER_SUBSCRIPTIONS, sorting, filterSet);

    // when
    List<Subscription> result = runTX(new Callable<List<Subscription>>() {
        @Override
        public List<Subscription> call() throws Exception {
            return dao.getSubscriptionsForMyCustomers(supplierUser, states,
                    pagination);
        }
    });

    // then
    assertEquals(NUM_SUBSCRIPTIONS, result.size());
    for (int i = 0; i < result.size(); i++)
        assertEquals(SUBSCRIPTION_ID_FOR_SUB_ID_CASE + i,
                result.get(i).getSubscriptionId());
}
 
Example 41
Project: yacy_grid_mcp   Author: yacy   File: Sort.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public Sort(String description) {
    this();
    if (description.startsWith("date:")) {
        this.option = Option.DATE;
        description = description.substring(5);
        if (description.startsWith("A")) {
            this.direction = SortOrder.ASC;
        } else {
            this.direction = SortOrder.DESC;
        }
    }
    if (description.startsWith("meta:")) {
        this.option = Option.METADATA;
        description = description.substring(5);
        int p = description.indexOf(':');
        if (p >= 0) {
            this.metafield = description.substring(0, p);
            description = description.substring(p + 1);
            if (description.startsWith("A")) {
                this.direction = SortOrder.ASC;
            } else {
                this.direction = SortOrder.DESC;
            }
        }
    }
}
 
Example 42
Project: jfreesane   Author: sjamesr   File: SaneImage.java    License: Apache License 2.0 6 votes vote down vote up
private static int frameSortOrder(Frame frame) {
  switch (frame.getType()) {
    case RED:
      return 0;
    case GREEN:
      return 1;
    case BLUE:
      return 2;
    case RGB:
      return 3;
    case GRAY:
      return 4;
    default:
      throw new IllegalArgumentException("unknown frame type " + frame.getType());
  }
}
 
Example 43
Project: oncokb   Author: oncokb   File: CustomizeComparator.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public static void sortKitTreatment(List<IndicatorQueryTreatment> treatments) {
    if (treatments == null)
        return;
    Collections.sort(treatments, new Comparator<IndicatorQueryTreatment>() {
        public int compare(IndicatorQueryTreatment t1, IndicatorQueryTreatment t2) {
            if (t1.getLevel() != null
                && t2.getLevel() != null
                && t1.getLevel().equals(t2.getLevel())
                && t1.getDrugs() != null
                && t2.getDrugs() != null
                && t1.getDrugs().size() == 1
                && t2.getDrugs().size() == 1
                ) {
                return compareKitTreatmentOrder(
                    t1.getDrugs().get(0).getDrugName(),
                    t2.getDrugs().get(0).getDrugName()
                );
            } else {
                return 0;
            }
        }
    });
}
 
Example 44
Project: flowmix   Author: calrissian   File: SortOp.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean equals(Object o) {

  if (this == o) return true;
  if (o == null || getClass() != o.getClass()) return false;

  SortOp sortOp = (SortOp) o;

  if (clearOnTrigger != sortOp.clearOnTrigger) return false;
  if (evictionThreshold != sortOp.evictionThreshold) return false;
  if (triggerThreshold != sortOp.triggerThreshold) return false;
  if (evictionPolicy != sortOp.evictionPolicy) return false;
  if (sortBy != null ? !sortBy.equals(sortOp.sortBy) : sortOp.sortBy != null) return false;
  if (triggerPolicy != sortOp.triggerPolicy) return false;

  return true;
}
 
Example 45
Project: titan1withtp3.1   Author: graben1437   File: AbstractLongListUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static LongArrayList mergeSort(LongArrayList a, LongArrayList b) {
    int posa=0, posb=0;
    LongArrayList result = new LongArrayList(a.size()+b.size());
    while (posa<a.size() || posb<b.size()) {
        long next;
        if (posa>=a.size()) {
            next=b.get(posb++);
        } else if (posb>=b.size()) {
            next=a.get(posa++);
        } else if (a.get(posa)<=b.get(posb)) {
            next=a.get(posa++);
        } else {
            next=b.get(posb++);
        }
        Preconditions.checkArgument(result.isEmpty() || result.get(result.size()-1)<=next,
                "The input lists are not sorted");
        result.add(next);
    }
    return result;
}
 
Example 46
Project: WeBASE-Node-Manager   Author: WeBankFinTech   File: NodeMgrTools.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * sort Mappings
 * @param mapping
 * @return List<MapHandle>
 */
public static List<MapHandle> sortMap(Map<?, ?> mapping) {
    List<MapHandle> list = new ArrayList<>();
    Iterator it = mapping.keySet().iterator();
    while (it.hasNext()) {
        String key = it.next().toString();
        MapHandle handle = new MapHandle(key, mapping.get(key));
        list.add(handle);
    }
    Collections.sort(list, new Comparator<MapHandle>() {
        @Override
        public int compare(MapHandle o1, MapHandle o2) {
            return o1.getKey().compareTo(o2.getKey());
        }
    });
    return list;
}
 
Example 47
Project: cloudstack   Author: apache   File: ClusterBasedAgentLoadBalancerPlanner.java    License: Apache License 2.0 6 votes vote down vote up
public static LinkedHashMap<Long, List<HostVO>> sortByClusterSize(final Map<Long, List<HostVO>> hostToClusterMap) {
    List<Long> keys = new ArrayList<Long>();
    keys.addAll(hostToClusterMap.keySet());
    Collections.sort(keys, new Comparator<Long>() {
        @Override
        public int compare(Long o1, Long o2) {
            List<HostVO> v1 = hostToClusterMap.get(o1);
            List<HostVO> v2 = hostToClusterMap.get(o2);
            if (v1 == null) {
                return (v2 == null) ? 0 : 1;
            }

            if (v1.size() < v2.size()) {
                return 1;
            } else {
                return 0;
            }
        }
    });

    LinkedHashMap<Long, List<HostVO>> sortedMap = new LinkedHashMap<Long, List<HostVO>>();
    for (Long key : keys) {
        sortedMap.put(key, hostToClusterMap.get(key));
    }
    return sortedMap;
}
 
Example 48
Project: cloudstack   Author: apache   File: HypervGuru.java    License: Apache License 2.0 6 votes vote down vote up
private NicTO[] sortNicsByDeviceId(NicTO[] nics) {

        List<NicTO> listForSort = new ArrayList<NicTO>();
        for (NicTO nic : nics) {
            listForSort.add(nic);
        }
        Collections.sort(listForSort, new Comparator<NicTO>() {

            @Override
            public int compare(NicTO arg0, NicTO arg1) {
                if (arg0.getDeviceId() < arg1.getDeviceId()) {
                    return -1;
                } else if (arg0.getDeviceId() == arg1.getDeviceId()) {
                    return 0;
                }

                return 1;
            }
        });

        return listForSort.toArray(new NicTO[0]);
    }
 
Example 49
@Test
public void multiply() throws Exception {
    List<Expression> args = Lists.newArrayList(getInvertedLiteral(10, PDataType.INTEGER), getLiteral(2));
    evaluateAndAssertResult(new DecimalMultiplyExpression(args), new BigDecimal(BigInteger.valueOf(2), -1));
    
    args = Lists.newArrayList(getInvertedLiteral(10, PDataType.INTEGER), getLiteral(2));
    evaluateAndAssertResult(new LongMultiplyExpression(args), 20l);
    
    args = Lists.newArrayList(getInvertedLiteral(10.0, PDataType.FLOAT), getLiteral(2));
    evaluateAndAssertResult(new DoubleMultiplyExpression(args), 20.0);
    
    args = Lists.newArrayList(getInvertedLiteral(10.0, PDataType.UNSIGNED_FLOAT), getLiteral(2));
    evaluateAndAssertResult(new DoubleMultiplyExpression(args), 20.0);
    
    args = Lists.newArrayList(getInvertedLiteral(10.0, PDataType.UNSIGNED_DOUBLE), getLiteral(2));
    evaluateAndAssertResult(new DoubleMultiplyExpression(args), 20.0);
    
    args = Lists.newArrayList(getInvertedLiteral(10.0, PDataType.DOUBLE), getLiteral(2));
    evaluateAndAssertResult(new DoubleMultiplyExpression(args), 20.0);
}
 
Example 50
Project: sarl   Author: sarl   File: SREsPreferencePage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sorts by SRE name.
 */
private void sortByName() {
	this.sresList.setComparator(new ViewerComparator() {
		@Override
		public int compare(Viewer viewer, Object e1, Object e2) {
			if ((e1 instanceof ISREInstall) && (e2 instanceof ISREInstall)) {
				final ISREInstall left = (ISREInstall) e1;
				final ISREInstall right = (ISREInstall) e2;
				return left.getName().compareToIgnoreCase(right.getName());
			}
			return super.compare(viewer, e1, e2);
		}

		@Override
		public boolean isSorterProperty(Object element, String property) {
			return true;
		}
	});
	this.sortColumn = Column.NAME;
}
 
Example 51
Project: sarl   Author: sarl   File: AbstractConversionTable.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sorts the type conversions by target type.
 */
private void sortByTargetColumn() {
	this.list.setComparator(new ViewerComparator() {
		@Override
		public int compare(Viewer viewer, Object e1, Object e2) {
			if (e1 != null  && e2 != null) {
				return e1.toString().compareToIgnoreCase(e2.toString());
			}
			return super.compare(viewer, e1, e2);
		}

		@Override
		public boolean isSorterProperty(Object element, String property) {
			return true;
		}
	});
	this.sort = Column.TARGET;
}
 
Example 52
Project: sarl   Author: sarl   File: IssueDatabaseExtensions.java    License: Apache License 2.0 6 votes vote down vote up
/** Sorts the given list and replies it.
 *
 * @param descriptions the list to sort.
 * @return {@code descriptions}.
 */
@Pure
public static List<IssueDescription> sort(List<IssueDescription> descriptions) {
	descriptions.sort((a, b) -> {
		int cmp = a.getShortDisplayCode().compareToIgnoreCase(b.getShortDisplayCode());
		if (cmp != 0) {
			return cmp;
		}
		cmp = a.getCodePrefix().compareToIgnoreCase(b.getCodePrefix());
		if (cmp != 0) {
			return cmp;
		}
		cmp = a.getSortLevel().compareTo(b.getSortLevel());
		if (cmp != 0) {
			return cmp;
		}
		return a.message.compareToIgnoreCase(b.message);
	});
	return descriptions;
}
 
Example 53
Project: L2jBrasil   Author: L2jBrasil   File: MultiSort.java    License: GNU General Public License v3.0 6 votes vote down vote up
public final double getStandardDeviation()
{
	if(getValues().isEmpty())
		return -1;

	List<Double> tempValList = new ArrayList<>();
	int meanValue = getMean();
	int numValues = getCount();

	for(int value : getValues())
	{
		double adjValue = Math.pow(value - meanValue, 2);
		tempValList.add(adjValue);
	}

	double totalValue = 0;

	for(double storedVal : tempValList)
	{
		totalValue += storedVal;
	}

	return Math.sqrt(totalValue / (numValues - 1));
}
 
Example 54
Project: vertexium   Author: visallo   File: ElasticsearchSearchQueryBase.java    License: Apache License 2.0 6 votes vote down vote up
private void applySortStrategy(SearchRequestBuilder q, SortingStrategySortContainer sortContainer) {
    SortingStrategy sortingStrategy = sortContainer.sortingStrategy;
    if (!(sortingStrategy instanceof ElasticsearchSortingStrategy)) {
        throw new VertexiumException(String.format(
            "sorting strategies must implement %s to work with Elasticsearch",
            ElasticsearchSortingStrategy.class.getName()
        ));
    }
    ((ElasticsearchSortingStrategy) sortingStrategy).updateElasticsearchQuery(
        getGraph(),
        getSearchIndex(),
        q,
        getParameters(),
        sortContainer.direction
    );
}
 
Example 55
Project: vertexium   Author: visallo   File: SortContainersComparator.java    License: Apache License 2.0 6 votes vote down vote up
private int compareProperty(QueryBase.PropertySortContainer sortContainer, VertexiumObject elem1, VertexiumObject elem2) {
    List<Object> elem1PropertyValues = toList(elem1.getPropertyValues(sortContainer.propertyName));
    List<Object> elem2PropertyValues = toList(elem2.getPropertyValues(sortContainer.propertyName));
    if (elem1PropertyValues.size() > 0 && elem2PropertyValues.size() == 0) {
        return -1;
    } else if (elem2PropertyValues.size() > 0 && elem1PropertyValues.size() == 0) {
        return 1;
    } else {
        for (Object elem1PropertyValue : elem1PropertyValues) {
            for (Object elem2PropertyValue : elem2PropertyValues) {
                int result = comparePropertyValues(elem1PropertyValue, elem2PropertyValue);
                if (result != 0) {
                    return sortContainer.direction == SortDirection.ASCENDING ? result : -result;
                }
            }
        }
    }
    return 0;
}
 
Example 56
Project: baymax   Author: tongbanjie   File: GroupbyResultSet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 分组排序
 *
 * TODO 优化:必须有order by 没有order by的 在解析的时候用 groupby的字段 作为orderby 重写sql,这样可以避免内存排序
 */
private void sort(){
    if (orderbyColumns == null || orderbyColumns.size() == 0){
        return;
    }
    if (groupbyValues == null || groupbyValues.length == 0){
        return;
    }
    Arrays.sort(groupbyValues, new Comparator<GroupbyValue>() {
        OrderByComparetor comparetor = new OrderByComparetor(orderbyColumns);
        @Override
        public int compare(final GroupbyValue v1, final GroupbyValue v2) {
            try {
                return comparetor.compare(v1, v2);
            } catch (SQLException e) {
                throw new BayMaxException("Group by ...Order by... 排序失败" , e);
            }
        }
    });
}
 
Example 57
Project: offer   Author: hackhu2019   File: Sort.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 实现插入排序
 * 将元素分为有序区和无序区两个部分
 * 每次从无序区取出一个数,将数据搬迁,将数字插入无序区有序位置,
 * @param nums
 */
public void insertSort(int[] nums) {
    if (nums == null || nums.length < 2) {
        return;
    }
    // 默认第一数为有序区
    for (int i = 1; i < nums.length; i++) { // 无序区
        int j = i-1;
        int temp = nums[i];
        // 逆序查找有序区插入位置,当 temp<nums[j] 时插入
        for (; j >= 0; j--) {
            if (nums[j] > temp) {
                // 将数据搬迁
                nums[j + 1] = nums[j];
            } else {
                break;
            }
        }
        nums[j+1] = temp;
    }
}
 
Example 58
Project: offer   Author: hackhu2019   File: Sort.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 归并排序
 * 将数组分为一各个小块,对每一块进行排序再合并
 * @param nums
 */
public void mergeSort(int[] nums,int start,int end){
    // 当元素数量小于 3 时,不再向下分
    if (end == start) {
        return;
    }
    if (end - start == 1) {
        if (nums[start] > nums[end]) {
            swap(nums, start, end);
        }
        return;
    }
    int mid = (start + end) >>> 1;
    // 排序左区间
    mergeSort(nums, start, mid);
    // 排序右区间
    mergeSort(nums, mid + 1, end);
    // 合并两个有序区间
    merge(nums, start, mid, mid + 1, end);
}
 
Example 59
Project: itext2   Author: albfernandez   File: PdfCollectionSort.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Defines the sort order of the field (ascending or descending).
 * @param ascending	an array with every element corresponding with a name of a field.
 */
public void setSortOrder(boolean[] ascending) {
	PdfObject o = get(PdfName.S);
	if (o instanceof PdfArray) {
		if (((PdfArray)o).size() != ascending.length) {
			throw new IllegalArgumentException("The number of booleans in this array doesn't correspond with the number of fields.");
		}
		PdfArray array = new PdfArray();
		for (int i = 0; i < ascending.length; i++) {
			array.add(new PdfBoolean(ascending[i]));
		}
		put(PdfName.A, array);
	}
	else {
		throw new IllegalArgumentException("You need a single boolean for this collection sort dictionary.");
	}
}
 
Example 60
Project: auth0-java   Author: auth0   File: UsersEntityTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldListUsersWithSort() throws Exception {
    UserFilter filter = new UserFilter().withSort("date:1");
    Request<UsersPage> request = api.users().list(filter);
    assertThat(request, is(notNullValue()));

    server.jsonResponse(MGMT_USERS_LIST, 200);
    UsersPage response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();

    assertThat(recordedRequest, hasMethodAndPath("GET", "/api/v2/users"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));
    assertThat(recordedRequest, hasQueryParameter("sort", "date:1"));

    assertThat(response, is(notNullValue()));
    assertThat(response.getItems(), hasSize(2));
}