Click here to Skip to main content
15,886,362 members
Everything / General Programming / Sorting

Sorting

sorting

Great Reads

by Christoph Buenger
Describes PHP application development with the free Scavix Web Development Framework (Scavix-WDF).
by Member 9294701
A simple, portable yet efficient Quicksort implementation in C
by brunofer2007
Easy way to sort nodes in a TreeView using a recursive function.
by DotNetLead.com
How to implement paging and sorting to yield good performance

Latest Articles

by Perić Željko
Sorting Multi-Dimensional Arrays in C# with QuickSort Sort Extensions
by Ramesh Bevara
An overview of a helper class to build dynamic order by clause in LINQ query in C#
by spore123
This is a fast multi-threaded quick-sort based algorithm
by The Sun God
Comparison of the various sorting algorithms on the basis of several factors

All Articles

Sort by Updated

Sorting 

12 Mar 2024 by Perić Željko
Sorting Multi-Dimensional Arrays in C# with QuickSort Sort Extensions
12 Sep 2023 by Ahmed Abdelsalam 2023
#include #include #include struct triangle { int a; int b; int c; }; typedef struct triangle triangle; void sort_by_area(triangle* tr, int n) { int i,j; double p; int *S = malloc(n * sizeof(int)); ...
10 Sep 2023 by Rick York
If I were you I would write some functions and macros to simplify the code and make it easier to read. Here are some that come to mind : double GetArea( triangle * pt ) { double p, area; p = ( pt->a + pt->b + pt->c ) / 2.0; area = sqrt(...
10 Sep 2023 by merano99
double p; int* S = malloc(n * sizeof(int)); p = (tr[i].a + tr[i].b + tr[i].c) / 2.0; S[i] = sqrt(p * (p - tr[i].a) * (p - tr[i].b) * (p - tr[i].c)); When assigning p, an arithmetic overflow can occur, since initially only int is...
31 Jul 2023 by OriginalGriff
Repost: Deleted. Please do not repost your question; use the Improve question widget to add information or reformat it, but posting it repeatedly just duplicates work, wastes time, and annoys people. I'll delete this one.
31 Jul 2023 by JOEY VERANO JR.
Hello everyone, hoping to answer my question. I am trying to rank group of scores in a datagridview containing 4 columns. I want the cells of the column B to have values as 1, 2, 3, based on the values of Column A. And for the Column D, I want...
31 Jul 2023 by Maciej Los
Well... I'd suggest to work on data instead of datagridview cells. Here is an idea: Sub Main() Dim numbers AS Integer() = New Integer(){8, 9, 1, 10, 11, 2, 12, 13, 3, 3, 5, 14, 15, 16, 17, 18, 8, 8, 8, 8, 19, 19} Dim result As List(Of...
23 Jul 2023 by Member 15840006
I got a tool from elsewhere It can list the pixel values used by the image i try to imitate it I use the memory method to extract image pixel colors values and remove duplicate values, but I can't achieve its sorting effect. Pixel Sort Sample...
28 Jun 2023 by Quinten Bakker (QB)
So I have a class node(name, vector, distance, prev) and i want to sort it by distance. And i have used some methods like sort or with a operator but nothing seems to work. Is there any other way to to sort a vector of classes? What I have...
28 Jun 2023 by Richard MacCutchan
I have simplified your node class and the following code builds and runs using Microsoft C++ compiler: #include #include #include #include class node{ public: std::string name; int...
28 Jun 2023 by k5054
I added a main function the above code vis: // .. QB's code up to here #include int main() { vector test; sort( test.begin(), test.end(), [](const node &a, const node &b){ return (a.distanceToStart
9 Jun 2023 by SamuelDexter
hello everyone. I am trying to rate a group of numbers in a datagrid containing two columns. I want the cells of the Coulmn B to have values as 1st, 2nd, 3rd etc, based on the values of Column A. For example: Col A Col B 80 2 305 1 23 ...
9 Jun 2023 by Member 15876310
Dim oDict As Dictionary(Of Integer, Tuple(Of Integer, Integer)) = DataGridView1.Rows().Cast(Of DataGridViewRow).GroupBy(Function(r) r.Cells(10).Value).OrderByDescending(Function(g) g.Key) _ .Select(Function(grp, index) New KeyValuePair(Of...
26 May 2023 by GOZMO
def dfs(i): status[i] = "visited" # mark the current node as visited for j in range(1,n+1): # iterate over all nodes if Graph[j][i] == 1: # if there is an edge from node j to node i if status[j] == "unvisited": # if...
11 May 2023 by ashan prabath
Problem You are given two non-decreasing sequences A = (A₁, A2,..., AM) and B = (B₁, B2,..., BN). You can choose any two indices i and j, and then swap A[i]; and B[j]. Note that the you can do the operations as many times as you want, and your...
11 May 2023 by Rick York
What I don't understand is what you are trying to do. An output of 4 from those two sequences makes no sense to me. I assumed you want to determine what the formula for the sequence is so something like what is f(x) to get M[x]. With that in...
11 May 2023 by OriginalGriff
While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for...
2 May 2023 by Shuvradip Sarma
public static int partition(int array[],int start,int end) ` { int pivot_index=(start+end)/2; int pivot=array[pivot_index]; int i=start; int j=end; while(i
18 Feb 2023 by merano99
Currently, this is C source code. The other programming languages according to the tag are irrelevant. There are several errors: // Str = (char**)calloc(5, sizeof(char)); need space for pointer, use n for size! Str = (char**)calloc(n,...
18 Feb 2023 by Addy__0
#include #include #include char **StringArray(char **arr, int size); int main() { char **Str; int n= 5; int i; Str= (char**)calloc(5,sizeof(char)); Str[0]= (char*) calloc(10, sizeof(char)); ...
17 Feb 2023 by OriginalGriff
Probably because it doesn't compile: you declare StringArray as returning achar** - but the function body does not have a return statement. If code doesn't compile, then it doesn't generate an EXE file - so what you are running is the previous...
17 Feb 2023 by CPallini
Quote: Str= (char**)calloc(5,sizeof(char)); That should beStr= (char**)calloc(5,sizeof(char *)); Might be there are other errors, as well. Anyway the code is not robust against user input.
23 Jan 2023 by DosNecro
import numpy as np import sys import timeit import DSAsorts import random REPEATS = 3 #No times to run sorts to get mean time NEARLY_PERCENT = 0.10 #% of items to move in nearly sorted array RANDOM_TIMES = 100 #No times to randomly...
23 Jan 2023 by Richard MacCutchan
Quote: I don't think this is the correct output that should be displayed. That is exactly the output that should be displayed, as shown by the code at: #main program if len(sys.argv)
23 Jan 2023 by OriginalGriff
Since we have no idea what your data contains or what output you actually get from the sort, we can't really help you. So, it's going to be up to you. Fortunately, you have a tool available to you which will help you find out what is going on:...
24 Dec 2022 by Ghost Ghost
you can try this: dynamic allDataRange = yourWorkSheet.UsedRange; allDataRange.Sort(allDataRange.Columns[1], Excel.XlSortOrder.xlDescending); to sort in certain range use the code below before the code above: Excel.Range last =...
24 Dec 2022 by riderwoman45
I am trying to sort an Excel worksheet using C# EPPLUS. I have reviewed the sort code method here I am doing this ` var startRow = 11; var startColumn= 1; var endRow= 150; var endColumn= 41; var sortColumn = 1; using...
22 Nov 2022 by Graeme_Grant
You could convert from RGB to HSV/HSB and use the (H)ue to create your color groups, then (S)aturation & (B)rightness to do your sub-sorts. Then once sorted, display the RGB value. ref: The HSB Color System: A Practitioner's Primer – Learn UI...
2 Nov 2022 by Log Hut Productions
How can I sort by an element in a list of numbers? For example, sort by element 2: ``` {[0, 13, 24], [0, 6, 8], [37, 2, 100]} ``` Expected result: ``` {[0, 6, 8], [0, 13, 24], [37, 2, 100]} ``` I tried using `key = lambda x:x[2]` but it did not...
2 Nov 2022 by CPallini
Note, the index of the second item of a list is 1 (instead of 2). Try l = [[0, 13, 24], [0, 6, 8], [37, 2, 100]] l.sort(key = lambda item: item[1]) print(l)
7 Oct 2022 by Member 15790844
I am currently working on a program that tests the speed and efficiency of four different sorting methods. Every sorting function will have a loop count and a swap count. I created a class in one file and implemented the member function in...
7 Oct 2022 by FreedMalloc
I have a few observations for your code. As commented above I don't know what "not always displayed" means. You don't mention the program aborting abnormally which I would think would be quite obvious. Other than that I see no reason the...
7 Oct 2022 by merano99
This will probably be a never-ending story. while (intArray[up]
22 Sep 2022 by Paul Lawrence Perez
We were tasked to apply the insertion sorting algorithm to an unsorted doubly circular linked list. I tried this algorithm given below; public void insertSort(){ Node cur = head; Node pointer; // this will hold the last...
22 Sep 2022 by OriginalGriff
Compiling does not mean your code is right! :laugh: Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email...
14 Jul 2022 by Member 15627552
#include #include #define MAX 20 void BuildHeap(int[], int); void heapify(int[], int, int); void swap(int *, int *); void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } int main() { ...
14 Jul 2022 by Patrice T
Quote: i tried so many things but still not able to fix the errors. What about stopping trying random things and rather watch your code preforming ? Your code do not behave the way you expect, or you don't understand why ! There is an almost...
14 Jul 2022 by Richard MacCutchan
The array declaration in the following code is not allowed in C. You can only declare fixed size arrays. scanf("%d", &n); int arr[n]; If you need a variable length array then you should use malloc thus: int* arr = malloc(sizeof(int)...
5 Jun 2022 by Ramesh Bevara
An overview of a helper class to build dynamic order by clause in LINQ query in C#
25 May 2022 by spore123
This is a fast multi-threaded quick-sort based algorithm
21 May 2022 by Member 15403309
Quote: How to sort an array like this ? I am getting array of strings with length but some of them are empty in markup. I need to avoid them. [0]=> string(6) " " [1]=> string(5) " " [2]=> string(1) " " [3]=> string(11) "The problem" ...
21 May 2022 by Richard MacCutchan
Use the String method: String.IsNullOrWhiteSpace(String) Method (System) | Microsoft Docs[^]
9 Apr 2022 by Kushal Das 2022
Create a program with multi-dimensional List to store customer details (customerId, customerName, customerAddress). This program to search the customer based on the customerName from a given array. Note: use Binary search and Insertion sort...
9 Apr 2022 by Patrice T
Quote: can u solve this question..give a proper code...plzzz Yes I can solve it. If you are learning how to beg, you are on good track. If you are learning programming, you have to know that it is like learning read/write, no one can learn it...
9 Apr 2022 by OriginalGriff
While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for...
9 Apr 2022 by Dave Kreskowiak
Nope. We're not here to do your work for you. Any attempt to get someone to write your code for you will result in a failing grade for you.
8 Mar 2022 by CoralSpring
after ES6: json.sort((a, b) => a._time) - b._time)); Taken from here: Sorting an array of objects by property values[^]
8 Mar 2022 by TzurS11
I have a JSON array and it looks like that: ```js { _time: 30, _customData: { //some more stuff here but its not important in this case }, }, { _time: 5, _customData: { //some more stuff here but its not...
6 Mar 2022 by TzurS11
Solution: json.sort(function (a, b) { return a._time - b._time; });
6 Mar 2022 by OriginalGriff
JSON is a data transfer format, it is not a data processor in any way. All it does is describe data in a language- and framework- independent way so that it can be produced by any system and read correctly on any other. As such, it's not...
17 Jan 2022 by Patrice T
Quote: I am new to programming and Algorithms and need assistance if possible. The assistance you are requesting is a 'do my homework for me'. Learning programming is like learning to read and write, no one can do it for you. Trial and error is...
17 Jan 2022 by OriginalGriff
While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for...
9 Dec 2021 by Admin BTA
I would like an efficient and non-invasive way of finding a median of a large array (a double array of size 300,000). What I have tried: I have tried an inefficient method: double Median(double[] xs) { Array.Sort(xs); return xs[xs.Length...
9 Dec 2021 by BillWoodruff
You could use the 'Median method in the open-source Math.NET Numerics library: [^]. For an interesting idea for an O(n) algorithm: [^] ... note: i have not used it.
9 Dec 2021 by Dave Kreskowiak
You don't have a choice here. Median values, by definition, require an ordered set to find them.
1 Dec 2021 by MUHAMMAD AMIRUL HAZMI BIN SHAMSUL MA'ARIF / UPM
This is my current code, and im stuck. It should be at least 3 different variables from the original data. What I have tried: class Node: def __init__(self, data=None, next=None): self.data = data self.next = next ...
1 Dec 2021 by OriginalGriff
Quote: and im stuck Stuck at what? Writing more code? Getting what you have to work? Physically glued to your desk? Quote: It should be at least 3 different variables from the original data. What is that supposed to mean? We have no idea. ...
29 Oct 2021 by Patrice T
Quote: How to optimize this code for speed any further Assuming the Elo ranking is positive values only: - At cost of count a little larger, min can be just removed from code. Assuming you know the range of values of Elo: - you can set max to a...
29 Oct 2021 by Weird Japanese Shows
Hello, I'm using counting sort for sorting elo rating of players, I've compared many different sorting techniques and decided to use counting sort. Even if counting sort is a little slower than insertion sort, because it's more stable and...
28 Oct 2021 by Rick York
Regarding your comments - they do not explain why you need to use shared_ptr. If you control the lifetime of the objects then you can safely use unique_ptr. I always make sure that I do (control object lifetimes) so I never, ever use shared_ptr...
28 Oct 2021 by Greg Utas
You could try creating locals for r.size() and count[r[i]->elo - min], but it probably won't matter if you're using a decent optimizing compiler. There's probably some overhead caused by boost::shared_ptr. A unique_ptr would be slightly faster,...
27 Oct 2021 by Nithish Karthikeyan
I'm coding a program to use selection sort in C program using functions and arrays but I'm getting error as undefined reference to swap What I have tried: #include #include void sorting(); void swap(int,int); int main() { ...
27 Oct 2021 by Patrice T
Quote: I'm coding a program to use selection sort in C program using functions and arrays but I'm getting error as undefined reference to swap Reason is that in C you can't define a function inside another function. #include #include...
27 Oct 2021 by CPallini
Try #include #include void sort(int array[], size_t len); void swap(int * pa, int * pb); enum { SIZE = 5 }; int main() { int arr[SIZE]; printf("enter your elements:\n"); for(int i = 0; i
26 Oct 2021 by OriginalGriff
Function prototypes such as void sorting(); andvoid swap(int,int); must have an identical signature to the function when it is actually declared: if it doesn't, then the two do not "match up" and the prototyped function is technically not defined...
5 Oct 2021 by Member 15382518
Shellsort�must be performed on the letters / keys «THANK» I can run this code using this function and get the result but doing shell sort in math , looks like more complicated. now: for each time the inner front loop is finished (ie...
5 Oct 2021 by OriginalGriff
While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for...
19 Jul 2021 by The Sun God
Comparison of the various sorting algorithms on the basis of several factors
18 Apr 2021 by Jelmapadru
I can't access the array. Uncaught TypeError: Cannot read property '1' of undefined var n = new Date(this[Y + 1][1]).getTime(); (4) [Array(2), Array(2), Array(2), Array(2)] 0: Array(2) 0: "Consectetur Adipiscing" 1: "Aug...
18 Apr 2021 by Richard Deeming
Consider the last two iterations of your inner loop on the first iteration of the outer loop: X === 0 On the penultimate iteration, Y === Length - 1; therefore, this[Y + 1] is equivalent to this[Length], which is beyond the end of the array. � ...
13 Apr 2021 by lil_mint
I am creating a program that sorts the user's input in increasing and decreasing order... I have tried the sorted() function but it would only sort 1 number. What I have tried: list=input("Enter your list:") print("Unsorted:", list.split()) ...
13 Apr 2021 by CPallini
The following program (Python 3) s = input() lnum = list(map(int, s.split())) print("Unsorted:", lnum) print("Sorted Ascending Order:") print (sorted(lnum)) print("Sorted Descending Order:") print(sorted(lnum, reverse=True)) executes this...
23 Feb 2021 by Bojjaiah
I am trying to sorting the string field from the List, But not working for me. Both results are returning the same. var objNotSort = getLiveData(); var objWithSort = SoryByOperation(getLiveData()).ToArray(); I cannot changes this field to...
23 Feb 2021 by OriginalGriff
The way I'd do it is to add IComparable to the list items class (tempLiveData in this case) and make it a requirement of the GenericSorterLive class type by adding a constraint: public class GenericSorterLive where T : IComparable { ......
23 Feb 2021 by Maciej Los
I'm using something like this (via Reflection): public static class RepoHelper where T: class { public static List SortBy(List lista, string fieldName, bool ascending = true) { Type t = typeof(T); PropertyInfo...
15 Jan 2021 by DotNetLead.com
How to implement paging and sorting to yield good performance
21 Dec 2020 by Azbilegt Chuluunbat
The challenge is not how to implement it. I know how. Instead, the question is what sorting algorithm needs to be used to get the fastest sorting performance especially when the number of words increase in the sentence. Quick sorting is believed...
21 Dec 2020 by CPallini
Quote: Quick sorting is believed to be the fastest It is statistically very good, anyway, there are alternatives. See, for instance Analysis of different sorting techniques - GeeksforGeeks[^]. Quote: when it comes to numbers to sort, but is...
28 Nov 2020 by Member 13151067
while (swapCounter != 0){ swaps = 0; for (int i = 0; i numbers[i+1]) { temp = numbers[i]; numbers[i] = numbers[i+1]; numbers[i+1] = temp; swaps...
20 Nov 2020 by whataweird
hi, this code won't compile correctly using std::sort and a struct. How do I solve this? #include #include #include #include struct StudentDataTypes { std::string name{}; int grade{}; }; int...
20 Nov 2020 by k5054
You need to tell sort how to compare the two structs. since there's no default comparison for non basic types. Do you want to sort by name or by grade, or by grade then by name, or ...? Probably the easiest way is to add an operator
20 Nov 2020 by Richard MacCutchan
The sort function does not know how to sort a StudentDataTypes structure. You must provide a comparator, see functions | Microsoft Docs[^].
28 Oct 2020 by Sandeep Mewara
Linear-time partition: A divide & conquer based selection algorithm
15 Sep 2020 by Patrice T
Quote: How do I resolve the bug in this selection sort logic By investigating what is going on with a debugger, it is a wanted skill. Check find_min, it is returning the position of minimum value in list, on every call. Try def...
15 Sep 2020 by 5atyam5rivastava
The following code block runs for only 1 iteration. Giving the output : [1,9,8,7,6,5,4,3,2,10] Kindly help in resolving the logical bug. What I have tried: ''' Program to implement Selection Sort The time complexity of above algorithm is O(n^2)...
15 Sep 2020 by CPallini
Try ''' Program to implement Selection Sort The time complexity of above algorithm is O(n^2) ''' def find_min (list0): min = 0 for i in range(1,len(list0)): if list0[i]
2 Sep 2020 by Member 14928977
Write a python program to define a tuple to accept 3 food product details such as Products name with their Price and Expiry date in a sub tuple then,arrange the tuple of tuple elements based on their price in ascending order. I should not use...
2 Sep 2020 by Sandeep Mewara
Using Bubble sort, it would be something like: def sortTuple(t): for i in range(0, len(t)): for j in range(0, len(t)-i-1): if (t[j][1] > t[j + 1][1]): #notice here, I have used index 1 to use price as the value ...
15 Jun 2020 by imabadjoke
public static void main (String [] args){ Scanner sc= new Scanner (System.in); System.out.println("Enter no. of Islands"); int n= sc.nextInt(); Graph g = new Graph (n); System.out.println("Enter no. of...
10 Jun 2020 by Richard Deeming
The built-in sort method takes a function which is passed two elements from the array and returns a value indicating their relative positions in the sorted list. Array.prototype.sort() - JavaScript | MDN[^] You can't pass extra parameters to...
10 Jun 2020 by Member 14859383
I am a beginner in JavaScript and I am trying to solve a task that I came up. I want to write a function that takes in an array like that: var array = [{date: '02.01.2017'}, {date: '11.11.2016'}, {date: '12.02.2001'}] and sorts the array in...
10 Jun 2020 by Patrice T
Quote: How to write a function that sorts elements by asc or desc depending on the parameter being called? My easiest is to use or write a sorting function in ascending order. you will find gazillions of algorithms and source code on internet....
16 Apr 2020 by Member 14804597
I think in the query it will be wrong. I was facing same issue because you should give tablenm.date column name in query LIKE SELECT * FROM student WHERE id='767' GROUP BY student.id ORDER BY student.date asc
16 Apr 2020 by User1454
Hi all, I have a datatable with 10 columns and the 9th column is date which is to be sorted in descending order. This gets sorted as expected. For a certain condition, the value should be provided with hyperlink. When i provide hyperlink, then it is sorting wrongly.
3 Mar 2020 by Vaclav_
Just an exercise, I am sure OP found better ways to spent his time. Start by finding a decent verbal definition of "bubble sort". Maybe you can even ask Mrs Google to get you a old fashioned flow chat of the algorithm. If decent , both should...
29 Jan 2020 by Patrice T
Quote: I'm new to computer science and I can't understand the concept of sorting 100 GB in 1 GB and I would like your help with solving this specific problem. Probably because there is no such concept. HDD storage and memory are essentially the same thing, the difference is that memory space is...
29 Jan 2020 by Member 14549747
I have a project where I am asked to sort a 100 GB file in 1 GB memory . I'm new to computer science and I can't understand the concept of sorting 100 GB in 1 GB and I would like your help with solving this specific problem. Thank you for your time . What I have tried: In sorting mergesort is...
29 Jan 2020 by RickZeeland
You can find examples in different languages here: external-sorting · GitHub Topics · GitHub[^]
29 Jan 2020 by OriginalGriff
The first thing to do is to start by looking at what you have to sort: what does the file contain that needs sorting? What does it need sorting by? Think about it: if you have a stack of mixed banknotes on your desk, there are many ways to sort them: by denomination, by colour, by size, by...
29 Jan 2020 by phil.o
The concept you need to do your task is called External sorting[^].