# Questions tagged [sorting]

23376 questions

-3

votes

1

answer

43

Views

### Problems with sorting an Array in Java

I´m a bloody beginner trying to write a lil programm to check if 2 words are anagrams. So far all the whitespaces within the words get deleted but apparently there's an error with my Arrays.sort() but I can´t see it. Why and where´s the error in my Arrays.sort() line and how could I solve it?
Edi...

1

votes

1

answer

186

Views

### TreeMap to Array. Does the array keep the order?

For every time, if I put the same values to the treeMap, the order of data in treeMap will be the same, right? No matter VM etc? I want to find out, if I convert treeMap to array on following way, I get sorted array, for every time in the same order for fixed treeMap.
Map treeMap = new TreeMap();
tr...

1

votes

1

answer

706

Views

### Getting the n largest values for groups [duplicate]

This question already has an answer here:
Pandas get topmost n records within each group
2 answers
I am looking to isolate the top 2 values per group for the following data.
Brand | Product | Rank
A | P1 | 1000
| P2 | 1210
| P3 | 2000
| P4 | 600
| P5 | 756
|...

1

votes

1

answer

37

Views

### How to fix this unsorted array in insertion sort?

I'm creating an insertion sort, the first one is working and returning a sorted array:
// {9, 8, 3, 13, 87, 12, 1, 99} the unsorted list
static int[] insertionSort(int[] a){
for (int i = 1; i < a.length - 1; i++) {
int element = a[i];
int j = i - 1;
while(j >= 0 && a[j] > element){
a[j+1] = a[j];
j-...

0

votes

1

answer

11

Views

### Optimizing SSIS package for millions of rows with Order by / sort in SQL command and Merge Join for millions of rows

Hi i am currently trying to optimize an SSIS package when i do an Upsert/delete which handels about 93+ million rows from a table in a remote MariaDB source.
The table also contains approximately 63 columns.
Currently i'm using Sort and Merge Join in my package but as i've read some guides its recom...

1

votes

2

answer

110

Views

### Mathematical solution to split X teams into 3 Teams per day

I am trying to split X number of Teams into 'play days' which consist of 3 teams per day
There is more than one solution to solve this for 15 teams.
What is the best approach to find all possible fixtures/match plans for team count 9-21?
Team count of 11, 14, 17 and 20 also cause problems, because t...

1

votes

2

answer

30

Views

### Sort numeric values except text in Bash

I have a csv file called prices.csv that looks like this:
Name, Price, Description
Apple, 2.85, fruit
Kiwi, 1.96, fruit
Banana, 0.99, fruit
Peach, Not available, fruit
Orange, 2.02, fruit
I would like to sort the second column (Price) in ascending order, except for the values that are 'Not available...

1

votes

1

answer

63

Views

### How to sort scores for high score board in a game

I'm writing a game in which you can have different users. Every time you play the game you submit a score. I want to have a high-score board that show the top 10 scores of all time. For instance:
A:[100,200,50]
B:[400,150,320]
C:[50,245,35]
What I want to achieve is:
B 400
B 320
C 245
A 200
B 150
A...

1

votes

2

answer

79

Views

### The sort function is not working properly

I have the following Array of results in contactArray variable. Here What I need is I'll need to sort the following records by LastModifiedDate of a particular record.
In the front end I have 3 records and First time I select only one record and do some manipulation in the back end and show again to...

1

votes

3

answer

38

Views

### Extract data from an array and include it to an object in javascript

I have a javascript object as follows.
{
name: 'tom',
age: 5,
fruits: [
{name: 'apple',qty: 4},
{name: 'orange',qty: 13},
{name: 'banana',qty: 3}
]
}
I am trying to convert this object into an object given below.
{
name: 'tom',
age: 5,
apple: 4,
orange: 13,
banana: 3
}
How do I achieve this? I have...

1

votes

3

answer

93

Views

### How to sort lists of objects using java

I have 2 lists which are holding the same objects but unordered and I want to sort them first before comparing them in order to check whether they are equals.
One item of each list looks like that:
first list:
AuditRow{dateStr='2019-04-15 11:16', userStr='admin', entityStr='Users'}
second list:
Aud...

1

votes

4

answer

50

Views

### How do you print the names of variables inside of an array?

I have made an array and placed some variables in it, and I want to get the name of the variable using the index number.
var a = 0;
var b = 0;
var c = 0;
var letters = [a,b,c]
console.log(letters)
I want to have it output '[ a, b, c ]' but this code actually outputs '[0, 0, 0]'
For more context, I p...

1

votes

3

answer

41

Views

### Sorting an object in an array through a method

This function sorts an array. First, the objects in which the country is equal to the one specified in the second argument should be displayed. Then all the rest. But I can not understand what is wrong?
const arr = [
{
'name':'BMW',
'price':'55 000',
'country':'Germany',
'certificate':'yes'...

3

votes

7

answer

106

Views

### Get an array sorted based on the content of another array

How can I sort the allGames array sorted to have the installedGames first?
const allGames = [
{ id: 2, name: 'game2' },
{ id: 1, name: 'game1' },
{ id: 4, name: 'game4' },
{ id: 3, name: 'game3' },
]
const installedGames = [
{ id: 2, name: 'game2' },
{ id: 3, name: 'game3' }
]
const sorted = allGame...

2

votes

1

answer

21

Views

### changing radix-sort base?

I'm trying to understand radix-sort but having problems understanding changing bases in implementing the actual code. This is the code i'm using to learn radix-sort and i'll try to explain what i don't understand.
This Code is by GeeksForGeeks:
// C++ implementation of Radix Sort
#include
using na...

-1

votes

1

answer

25

Views

### How to Compare sort executions time unpredictable results in C

I am trying to write in file the execution time of the two bellow sorts (qsort & insertion) with giving them as parameters a random array. But the results each time of the second phase of clock() - clock() is 0 or something that doesn't seems right. For example if i have only the calculation of ins...

1

votes

1

answer

24

Views

### Is there a way to enumerate a list or dictionary that share the same index?

I want to enumerate a list or dictionary, if the items share the same value or are equal I want them to use 1 index.
This is my code:
def print_data(league_results):
for i, (team, points) in
enumerate(sorted(league_results.items(), key=lambda x: x[1],
reverse=True), 1):
if points == 1:
i = i
print...

1

votes

1

answer

2.1k

Views

### Sorting array of objects by property in MATLAB? [duplicate]

This question already has an answer here:
Matlab - sort cell array of objects by property
1 answer
I have an array of objects, each with various properties, and I would like to figure out how to run 'sort' on the array, specifying a specific property of each object to sort by.
For example, say my...

13

votes

3

answer

613

Views

### Sorting the characters in a UTF-16 string in Java

TLDR
Java uses two characters to represent UTF-16. Using Arrays.sort (unstable sort) messes with character sequencing. Should I convert char[] to int[] or is there a better way?
Details
Java represents a character as UTF-16. But the Character class itself wraps char (16 bit). For UTF-16, it will be...

4

votes

3

answer

188

Views

### how to find the median of a vector if the method is const?

I've created a method called Collect that adds a bunch of values to a vector (shown below)
void Median::Collect(double datum)
{
myVector.push_back(datum);
}
I need to create a method that calculates the median of all of the values I collected in the vector in the method above. The function definitio...

1

votes

2

answer

471

Views

### Quick Sort Algorithms - Many different ways of doing the same thing?

Am I correct in saying that there would be many ways to perform a Quick Sort?
For argument sakes, lets use the first textbook's numbers:
20 47 12 53 32 84 85 96 45 18
This book says to swap the 18 and 20 (in the book the 20 is red and the 18 is blue, so I've bolded the 20).
Basically it keeps moving...

1

votes

2

answer

105

Views

### heap sort C - improper output

I'm trying to implement heap sort for an array of 10 elements in ascending order.
I'm following these steps -
heap_sort(arr,size_array):
build_max_heap(arr)
for(parent=size_array to 1):
swap(arr[1],arr[parent])
size_array = size_array - 1;
max_heapify(arr,1,size);
But my output is totally messed up...

1

votes

3

answer

47

Views

### Custom sorting in JavaScript homework question

Write a function named sort_by_average_rating that takes a list/array of key-value stores as a parameter where each key-value store has keys ratings, budget, and box_office where budget and box_office are integers and ratings is a list of integers. Sort the input based on the average of the values i...

1

votes

3

answer

6.6k

Views

### Lexicographically sort C#

I have this code for sorting strings:
class Program
{
static void Main()
{
int x = Convert.ToInt32(Console.ReadLine());
List sampleList = new List();
for (int i=0; i

0

votes

3

answer

23

Views

### How do i properly Use a field to sort my array

I have an Array i will Like to sort with a field in the array But its not working
var data = [{tm: '09:00', tr: '30.34', rd: '73.23'},
{tm: '09:10', tr: '30.45', rd: '70.77'},
{tm: '09:50', tr: '29.95', rd: '75.70'},
{tm: '09:40', tr: '29.95', rd: '75.70'},
{tm: '01:50', tr: '29.95', rd: '75.70'},
{...

6

votes

0

answer

104

Views

### How can I optimize parallel sorting to improve temporal performance?

I have an algorithm for parallel sorting a list of a given length:
import Control.Parallel (par, pseq)
import Data.Time.Clock (diffUTCTime, getCurrentTime)
import System.Environment (getArgs)
import System.Random (StdGen, getStdGen, randoms)
parSort :: (Ord a) => [a] -> [a]
parSort (x:xs) = force...

1

votes

2

answer

2.7k

Views

### sort a string array using numpy

I want to sort a string array using numpy by the length of the elements.
>>> arr = ['year','month','eye','i','stream','key','house']
>>> x = np.sort(arr, axis=-1, kind='mergesort')
>>> print(x)
['eye' 'house' 'i' 'key' 'month' 'stream' 'year']
But it sorts them in alphanumeric order. How can I sort...

1

votes

2

answer

289

Views

### How to sort with incomplete ordering?

I have a list of elements to sort and a comparison function cmp(x,y) which decides if x should appear before y or after y. The catch is that some elements do not have a defined order. The cmp function returns 'don't care'.
Example: Input: [A,B,C,D], and C > D, B > D. Output: many correct answers, e....

1

votes

3

answer

1k

Views

### Unable to sort date time in javascript with format dd/MM/yyyy HH:mm

I am not able to sort by latest date time in javascript.
Below is my json :
let jsonStr = [{id:1,date:'04/04/2017 17:47'},
{id:2,date:'05/01/2015 12:35'},
{id:3,date:'31/02/2017 10:00'},
{id:4,date:'31/02/2017 12:00'}];
Expected result : Latest date time should be first in the list
04/04/2017 17:47...

1

votes

1

answer

42

Views

### sort() in ES6 sorts items in a wrong way when there are too many objects in the array

This is a sample array with 8 objects inside. Now, I want to sort them in ascending order. And I get the result perfectly in console.
const array =
[{'lead_location':'a'},{'lead_location':'rta'},
{'lead_location':'van'},{'lead_location':'svan'},
{'lead_location':'avan'},{'lead_location':'yvan'},
{...

1

votes

1

answer

40

Views

### Select unique values in dataframe based on sorted value

Has anyone selected unique values from a dataframe based on a second value's highest value?
Example:
name value
cheese 15
pepperoni 12
cheese 9
tomato 4
cheese 3
tomato 2
The best I've come up with - which I am SURE there's a better way - is to sort df by value descending, extract df$name, run uniqu...

1

votes

3

answer

65

Views

### How to sort a vector according to a given sequence in R

I'm trying to organize a sequence of data according to a given sequence. For example, the given sequence I have is
set.seed(1)
given_seq

1

votes

2

answer

79

Views

### Sort DataFrame on column of intervals

My output looks like this:
binnedb Proba-A Proba-B Esperance-A Esperance-B
0 (0.0101, 0.0202] 0.547826 0.539130 0.007817 0.007693
1 (0.0302, 0.0402] 0.547826 0.539130 0.005963 0.005854
2 (0.0201, 0.0302] 0.547826 0.539130 0.008360 0.008227
What I would like to d...

1

votes

1

answer

32

Views

### Sorting a list with reversed stages

In python, one can perform a sort on a list using sorted(list) or list.sort(). These functions support sorting by various stages (primary sort, secondary sort, etc.). I know that one can reverse the sort by supplying reversed=True to the function.
My question is: How can I sort a list and reverse a...

1

votes

2

answer

93

Views

### Groupwise sorting with SQL

I need to sort data groupwise. For my knowledge this can not be achieved with sort by multiple conditions and also a group does not what I need, as I don't want to reduce the records but sort them while keeping groups together. Look at the following data:
Group Data1 Data2
a 1 5
a...

1

votes

3

answer

51

Views

### Is there a functionality in mysql to order by to specific row?

I have a table e.g students:
id | name
-- |-----
1 | A
2 | B
3 | C
4 | D
5 | E
6 | F
7 | G
8 | H`
How to wite a sql in mysql so that first 4 students are order by id ascending and rest order by id descending output should be something like this
id | name
---|------
1 | A
2 | B
3 | C
4...

1

votes

3

answer

68

Views

### Javascript Array sort() does not sort array of strings correctly [duplicate]

This question already has an answer here:
How to perform case-insensitive sorting in JavaScript?
13 answers
I have the following JavaScript code:
const ary = ['Kevin', 'brandy', 'Andrew'];
const nary = ary.sort();
console.log(nary);
I expected the output of the above code to be ['Andrew','brandy',...

1

votes

2

answer

49

Views

### How to sort array values nested inside a hash with different keys?

I have an html table showing outage start and end times with different types of outages. Currently, I am sorting the outages in order of outage type, but I would like to be able to sort them by earliest to latest start times. The times in each start and end will already be in order, but I am trying...

1

votes

1

answer

53

Views

### Sorting dictionary by the closest value

I have a dictionary of the keys and values, that values are from 0.0 to 1.0 like this the one below:
{'item1': 0.88, 'item2': 0.4, 'item3': 0.49, 'item4': 0.75, 'item5': 0.32, 'item6': 0.9}
I had to sort it by the value closest to 0.5.
I know how to sort dictionary ascending or descending from the g...

1

votes

5

answer

82

Views

### sort text file by groups of 2 lines

I have a file with the following structure:
A 35 74 dsadasd/1 0 +
A 95 74 dsadasd/2 0 -
B 75 159 dsadasd/2 0 +
B 78 852 dsadasd/1 0 -
C 12 789 dsadasd/1 0 +
C 91 546 dsadasd/2 0 -
A 87 52 dsadasd/2 0 +
A 52 15 dsadasd/1 0 -
I would like to...