Click here to Skip to main content
15,867,568 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 Score

Sorting 

31 Oct 2014 by Christoph Buenger
Describes PHP application development with the free Scavix Web Development Framework (Scavix-WDF).
13 Oct 2013 by Member 9294701
A simple, portable yet efficient Quicksort implementation in C
15 Mar 2011 by Sergey Alexandrovich Kryukov
Don't use ArrayList. This type is obsolete since generics were introduced in v.2.0. Why do you need all those problems with type casting?Instead, use the generic class System.Collections.Generic.List, http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx[^]. For sorting use some of the...
11 Sep 2011 by brunofer2007
Easy way to sort nodes in a TreeView using a recursive function.
13 Apr 2012 by VJ Reddy
The reason is in the SortedList, the key is added as an integer. So, the order will be 7, 31, 32, 33. Whereas, in the DataTable the value is text, hence, the order is 31e, 32e, 33e, 7i.To get the same sort as in data table, add the key as text i.e.emp.Add(key, type);where key is 31e,...
25 Apr 2012 by VJ Reddy
The Array.Sort(Of TKey, TValue) Method (TKey(), TValue(), IComparer(Of TKey)) explained here http://msdn.microsoft.com/en-us/library/x8kwfbye.aspx[^] can be used for this purpose. In the present case, as the sorting is to be done in Descending order IComparer is required, which is explained here...
8 Aug 2013 by Antariksh Verma
Hi ,After doing lot of R&D in Kendo UI i got that if we want sorting ,filtering and paging on client side we have to add .ServerOperation(false) so that all functionality like Sorting and filtering works on client side.
15 Jan 2021 by DotNetLead.com
How to implement paging and sorting to yield good performance
16 Mar 2011 by Espen Harlinn
Using IComparer, as SAKryukov mentioned, is a good idea, and in your case it should look something like this:using System;using System.Collections.Generic;namespace Harlinn.CP.ScoreTest{ public class Score { private string name; private double...
1 Oct 2015 by phil.o
If only CodeProject had one of the best articles on the subject[^].
1 Oct 2015 by CPallini
You know the major sorting algorithms have been studied and their performance is known (I would reccomend the oldie-goldie Wirth's book[^] as starting point).If you are really curious to measure the performance on your set of data then no one prevents you in doing that.
28 Nov 2015 by Patrice T
I see 2 reasons for your program not listing the numbers sorted.First: you list the numbers before sorting them.Second: the sort routine is bugged to the core. The general layout is of an insertion sort, but it is bugged and don't work.Since it is HomeWork, no solution, but advices.-...
23 Feb 2016 by Patrice T
The output is correctYour mistake is that you sort a list of strings, not a list of numbers.so "6" fall between "54" and "77"a sort on strings is alphabetical.
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 ...
28 Oct 2020 by Sandeep Mewara
Linear-time partition: A divide & conquer based selection algorithm
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
12 Mar 2024 by Perić Željko
Sorting Multi-Dimensional Arrays in C# with QuickSort Sort Extensions
7 Dec 2009 by Pete O'Hanlon
I would look at using the KeyPress event on the textbox and set e.Handled=true if the key was a spacebar (e is the KeyPressEventArgs for the event handler). Your code might look something like this:private void TextBox1_KeyPress(object sender, KeyPressEventArgs e){ e.Handled = e.KeyChar ==...
7 Dec 2009 by jasonpang2011
To add onto the answer above, the KeyPress event handler won't work unless you set KeyPreview to true. The KeyPreview property is on the Windows Form (click your form, look to the property box to the right, find KeyPreview, and set it to True). Or you can manually add the following to the...
7 Dec 2009 by AspDotNetDev
VB does not use a double equal sign to test for equality. It only uses a single equal sign. Try:e.Handled = (e.KeyChar = " ")Also, it doesn't use semicolons to end lines.
17 Feb 2010 by #realJSOP
Try this:emails = (from p in DatabaseConnection.Emails where p.Newsmail == true select p).Distinct();
16 Mar 2011 by #realJSOP
Don't use an ArrayList - use a generic collection. Once you've converted your code, check out this tip/trick:A Generic Comparison Class for Collection Items[^]
26 Mar 2012 by Søren Gullach
A Shunting yard algorithm in C#
17 Apr 2012 by Fredrik Bornander
If you have a Player class that looks something like this;package my.company;public class Player { private final double x; private final double y; public Player(final double x, final double y) { this.x = x; this.y = y; } public...
16 Sep 2013 by Philippe Mori
The easiest way to do it is to uses Link to objects.myContainer .OrderBy(x => x.FirstColumn) .ThenBy(x => x.SecondColumn);Alternatively, you can define your own comparison operator that will compare first column and if there is a match it will compare next column until the answer is...
16 Sep 2013 by Maciej Los
I would suggest you to use OLEDB[^] drivers with T-SQL command like this:SELECT Field1, Field2, ... FieldNFROM MyFile.csvORDER BY Field1How to: Use OleDb to import text files (tab, csv, custom)[^]Read Text File (txt, csv, log, tab, fixed length)[^]
19 Sep 2013 by Prasad Khandekar
Hello Ganesh,For jQGrid if datatype other than "local" the sorting needs to get handled on the server side. For client side sorting the datatype must be "local" and each sortable column must have the sorttype property set (see this[^] link to know more about server side paging and client...
17 Oct 2013 by Javier Tirado Pampín
This article talks about how to solve the filter problem in Telerik MVC Extensions control suite
16 Jan 2014 by Codes Of Shadows
Header Style Combo Box Drop Down Filter Button
3 Mar 2014 by BillWoodruff
Yes, you can sort the values in an Enum for display in a ComboBox alpha-numerically, or any other way you want:// requires Linq// preserve the current ComboBox selectionprivate V currentVName;private void Form1_Load(object sender, EventArgs e){ var vAry =...
23 Mar 2014 by BillWoodruff
After playing with the CheckedListBox a while, I am convinced you will find it much easier to implement this using two ListBoxes. The ListBox offers you built-in sorting by setting its 'Sorted Property to 'true.If you still really wish to use a CheckedListBox, hopefully this code will give...
25 Mar 2014 by CHill60
As Richard MacCutchan said, you will need to design a Database first to capture the information about each meal each user has had.Here's a link to a beginners guide to databases[^]Think carefully about the tables you will need and what sort of information you will need to...
24 May 2014 by CPallini
I wouldn't choose the different path inside the sort function. I would use instead different comparators. For instance, have a look at the following code:#include #include #include using namespace std;struct my_struct{ my_struct(int i, string...
8 Oct 2014 by Thomas Daniels
Take a look at these CodeProject articles:Natural Sort Comparer[^]Sorting Strings for Humans with IComparer[^]
18 Feb 2015 by PIEBALDconsult
Here's an example of a class that uses two Dictionaries.I do caution you about your first criterion as I'm sure my solution will have trouble if a value's priority is changed. DumbStuff.PriorityDictionary d = new...
17 Jul 2015 by Richard Deeming
Your timezone data doesn't contain the offset value, so you'll need to extract it from the label.Something like this should work:timeZone.sort( function( a, b ) { var re = /^\(GMT([+-]\d{1,2}):(\d{1,2})\).*$/; var aOffset = parseFloat(a.label.replace(re, "$1.$2")); var...
22 Nov 2015 by Patrice T
Obviously, your own code is like a blackbox to you. It don't do what you expect.What follow is not directly a solution to your problem, but a key that will help you to understand by yourself what is wrong.The debugger is your friend. It will show you what your code is really doing.Follow...
27 Nov 2015 by OriginalGriff
"didn't sort by real number !"OK - but we have no idea what data you were looking at, or how you decided that it didn't work.Plus, it's your homework, so it's a good idea that you sort this yourself - you will learn a lot more than if I fix it and give you the sorted code.So, its going...
23 Feb 2016 by F-ES Sitecore
This will convert the string to a number when doing the comparison;if (int.Parse(a.ElementAt(j)).CompareTo(int.Parse(a.ElementAt(j + 1))) > 0)However it will error if you add somenone non-numeric to the list. For a number sort you're best using LinkedList x = new...
27 Apr 2016 by OriginalGriff
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.Try it yourself, you may find it...
27 Apr 2016 by CPallini
Don't search for code. Study algorithms instead. An oldie-goldie book is Wirth's one: "Algorithms + Data Structures = Programs - Wikipedia, the free encyclopedia"[^]. It could be a staring point, covering all but string matching.
4 Jun 2016 by OriginalGriff
Um...that's some odd code you have there!Start with your first method:int my_array(int _array[],int size ) { for(int i=0;i { return _array[i]; } }It always returns the first element in the array, unless the size is negative, in which case...
20 Jun 2016 by KarstenK
To achieve your own sort order you must overwrite the sorting algorithm, by overwriting the comparison operator "
3 May 2017 by InvisibleMedia
An algorithm for sorting integers with a complexity less than O(n log (n))
14 Aug 2017 by CHill60
You appear to have at least 6 tables with exactly the same schema. This is usually a sure sign that your database design needs some attention. From what I can see all of this information could be (and should be) stored in a single table. Add another column that indications the "BuildingType" -...
4 Apr 2019 by OriginalGriff
Take your string, and use Split, then sort the array: string query = @"id = 657ec95c439eb4a76e48c5ea7 & amount = 1 & notify_status = success & currency = USD & time = 20190403095815 & reference = 190403175800PTM03428 & notify_id = D0000036639 - a6d98e5d0a08d3e8850f & fields = id %...
29 Jan 2020 by phil.o
The concept you need to do your task is called External sorting[^].
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...
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]
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...
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...
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...
23 Apr 2010 by CyberSamuraiii
Hi all,I've landed in a situation where i need the top N number of items in an array, work on those items and reinsert (or update) them back at the exact same indices. I realized that the easiest way would be to sort an array 1st then pick N number of the highest elements, but I find my...
22 Apr 2010 by #realJSOP
With the pitiful amount of info you've provided, the best I can suggest is that you look into using a Dictionary object instead of an Array.
1 Jun 2010 by Samanvay
For this you need to pass Dropdownlist value to XSL using parameter and based on param value which you have received in XSL apply xsl:sort statement. Roughly you need to do following C# CODEXslCompiledTransform tras = new XslCompiledTransform();XsltArgumentList argList = new...
8 May 2011 by OriginalGriff
It's a bit simpler than that!This example sorts a list of Points by looking only at the X distance: List p = new List(); ... // Fill p with Points! p.Sort(new PointComparer()); ... public class...
8 May 2011 by ukram2
Ok, found a solution that looks more or less ok to me. I used another class, point_sorter to hold the third point and defined a Comparison Delegate compatible function there to compare the two points.using System;using System.Collections.Generic;using System.Linq;using...
15 Jul 2011 by #realJSOP
If all of your data will fit in available memory, you could retrieve all of the data you need to display, and then extract only the items that will fit in a page. Psuedo code:0) retrieve data 1) Calculate number of pages you have - Math.Min(1, Math.Floor(records_retrieved /...
22 Sep 2011 by Sergey Alexandrovich Kryukov
The bug is very apparent: this is the lineCurr.Next := Sorter(Curr.Next);It works only of Curr assigned to Head is NULL. In all other cases, nothing happens to pointers before Sorter calls you with the same very parameter always equal to initial Head. Not going into further detail,...
28 Sep 2011 by Stefan_Lang
At a glance, I'd say you should change void add(HeapNode * child) { // if the new value is bigger than this value if(child->value > value)to void add(HeapNode * child) { // if the new value is smaller than this value if(child->value
17 Mar 2012 by ProEnggSoft
An alternative is to create one field in the database for color code, say ColorCode, assign the values say 1 - Green, 2 - Yellow, 3 - Red. Then based on this field, apply color to the rows of the DataGridView in CellFormatting event.private void dataGridView1_CellFormatting(object...
19 Mar 2012 by ProEnggSoft
You cannot sort the hidden column visually by clicking on the DataGridView as the column is not visible. One of the following options can be used, to sort the hidden column, using the bindingSource1 to which the DataGridView is bound.Option1.Use buttons, say Button1 and Button2 to sort...
2 Apr 2012 by Abhinav S
To customize sort in a datagridview, go through this article - How to: Customize Sorting in the Windows Forms DataGridView Control[^].
17 Apr 2012 by Leonardo Paneque
Use a distance function D=sqrt((x1-x2)^2+(y1-y2)^2) and keep the closets ones on the array of K elements.Depending on what your final problem is you could either compare with all and sort, then grab first K, or do it in one pass while putting new ones in a sorted list. up to you.hope it helps.
25 Apr 2012 by Member 8312096
Dear All,I have two arrays (array1 and array2)with double type data. I want to sort array1 to ascending order, and array2 with corresponding to the array1 indexes. Is this possible? Example below,Array1(0) = 2.30 Array1(1) = 4.20Array1(2) = 1.90Array1(3) = 0.20Array1(4) = 0.88...
2 Oct 2012 by wkiess01
How to sort a data bound combobox
18 May 2012 by smrizvi1
Hey everyone! i stuck here with a thing. I use this code in visual c++ to search a book by its author. I have used the approach of bubble sorting then binary searching.Alright, now this is what i have. what i want to do now is to search a particular BOOK by its author without using the...
24 Jul 2012 by _Amy
Hi,Use this://Dropdownlist selected value changed event. This can be done on button click event also.protected void DropDownList1_SelectIndexChanged(object sender, EventArgs e) { gvSorting.Sort(DropDownList1.SelectedValue, SortDirection.Ascending); ...
5 Dec 2012 by amrita_thakur
Hi...I have a WPF Datagrid which I've grouped by a column ProductName. I want to perform sorting on UploadDate which is a datefield. The issue here is on clicking on sort I want the data to be sorted on UploadDate within the groups, by the datagrid sorts the data based on the ProductName, on...
16 Dec 2012 by Basil_2
How to choose an STL sorting algorithm.
18 Dec 2012 by deepakdynamite
Hello Everyone,I want to sort few records which actually contains Duration but they are in nvarchar datatype.. For eg. Select '33:14:14' as 'Duration'UNIONSelect '1:16:36' as 'Duration'UNIONSelect '0:3' as 'Duration'UNIONSelect '0:29' as 'Duration'UNIONSelect '02:12:39'...
18 Dec 2012 by Amir Mahfoozi
Hi,One solution is converting your data to seconds either on the fly or by using a user defined function.Here is a SQL statement that converts your data to seconds on the fly :SELECT * FROM (SELECT Duration ,CASEWHEN CHARINDEX(':',Duration )=0 THEN CAST (Duration AS...
24 Mar 2013 by Sandeep Mewara
Following will help you: MSDN: GridView Examples for ASP.NET 2.0: Paging and Sorting the GridView's Data[^]Similar question with answers: Sorting in Gridview Asp.net C#[^]
19 Jun 2013 by OriginalGriff
How large?If it's a couple of megabytes, then try just using Split and Sort: Stopwatch sw = new Stopwatch(); sw.Start(); string s = File.ReadAllText(@"D:\Temp\MyText.txt"); string[] data = s.Split(' ', '\n'); Array.Sort(data); ...
1 Oct 2013 by ridoy
You can have a look at:How do I sort an observable collection?[^]Sorting values of ObservableCollection (Reactive Extensions)[^]
4 Mar 2014 by Maciej Los
Have a look here: Filtering and Sorting Directly in Data Tables[^]
17 Mar 2014 by CPallini
You may use a dictionary to map the Type Ids to your own order criterion, e.g.Dictionary mo = new Dictionary{ { 3, 0 }, { 5, 1 }, {2,2}, {4,3}, {6,4} };Thendocuments.OrderBy(d => mo[d.Type.Id])
11 Apr 2014 by iratus7
I have a bindinglist of keyvaluepairs that is filled dynamicaly. BindingList> Homelist = new BindingList>(); foreach (ListItem item in listBox2.Items) { Homelist.Add(new KeyValuePair(item.Id, item.Name)); ...
11 Apr 2014 by CHill60
For sorting the list on value rather than key just provide an appropriate compare method ... have a look at this example http://www.dotnetperls.com/sort-keyvaluepair[^]If you want to treat the first 5 items differently to the rest then you could split the list into two separate ones before...
11 Apr 2014 by iratus7
public int Compare(KeyValuePair a, KeyValuePair b) { return a.Value.CompareTo(b.Value); } List> Playinglist = new List>(); for (int i = 0; i
20 Apr 2014 by CPallini
Once you have fixed the code (as it stands it doesn't even compile), no one prevents you using the std::sort[^] function.
29 May 2014 by Nirav Prabtani
try this.. :) DataSet ds=new DataSet(); DataTable dtTable = new DataTable(); dtTable = ds.Tables[0]; DataView dv = dtTable.DefaultView; dv.Sort = "ColumnName" + " " + "ASC"; //OR dv.Sort =...
8 Oct 2014 by Manu Prasad
var strTest = new List { "B1", "B2","b3","0", "B3", "B10","B20","B90","GB2","B9","B21","GB1","GB11" };I need to sort the above list as "0, b3,B1, B2, B3, B9, B10, B20, B21, B90, GB1, GB2,GB11"Can anyone help me with this one.Thanks in Advance,
29 Oct 2014 by V5709
Hi.. Make little bit change in your code line ..change it to lstRecData = lstRecData.OrderBy(x => x.strRecPriority).ToList();Here is the sample codeclass Program { static void Main(string[] args) { List lstRecData = new...
29 Oct 2014 by Member 11091184
HiJust avoid Reverse().it will be fine.List lstRecData = lstRecData.OrderBy(x => x.strRecPriority).ToList();
21 Nov 2014 by PIEBALDconsult
Quote:unsortDon't alter the array -- make another array with the indices of the first array and alter that -- it's kind of a linked list that way.int[] i = new int[] { 20,5,90,7,44,81 };int[] j = new int[] { 1 , 3 , 0 , 2 , 4 , 5 };
18 Feb 2015 by Herbisaurus
I need a collection of objects that will: * allow get, set functionality object via a key (like in a dictionary)* I need to iterate through the collection in a sorted manner, ordered by a "Priority" value* the priority allows multiple values. * the keys can be an int or a string, it...
3 Mar 2015 by OriginalGriff
Um.You do realise that that code does a total of nothing?for (int i = 0; i
7 Apr 2015 by Sergey Alexandrovich Kryukov
So far, I came up with only some trivial solution: use one more intermediate int object. This is not prohibited by the problems formulation. You can use it to represent a kind of "array of digits". You have only 10 digit, so a digit object needs only 4 bits (half-byte) to represent. But maximum,...
11 Apr 2015 by User 59241
This will do it. It will handle multiple occurrences of digits but not 0 of course (at present 0 is ignored). If required 0 would have to be placed after 9. Easy enough to do. #include int main () { const __int64 input = 456120; __int64 output = 0, temp1; int len =...
4 May 2015 by Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)
Something like this...dt.DefaultView.Sort = "YourColumnName ASC"; // DESC for descending.
26 Jul 2015 by Artem Kulikov
Hello. You should notice, that in your code - you will get only one contour.For your purpose you should fistly get all contours, and after that order them. Check this code:var allContours = new List>(); for (var contours = image.FindContours(); contours !=...
1 Oct 2015 by George Jonsson
Looks like home work to me.Why not add time measure to your code, implement different algorithms and measure the outcome for the different cases.That should give you the answer which method is most efficient for each case (or maybe for all).
27 Nov 2015 by mbue
cur->prev = p; if(cur->prev != NULL) it is strongly recommended to use human readable names - so you can see 'cur' is 'p' now. if(p->prev != NULL) p->prev->next = p;regards.
27 Nov 2015 by Mehdi Gholam
Read this : http://stackoverflow.com/questions/7851387/sorting-complex-numbers[^]
28 Nov 2015 by Andreas Gieriet
Never ever reinvent sorting yourself. If this is a homework assignment, do it according to your text book. If it is otherwise needed, use any existing sorting, i.e. by using some of the existing Sort functions, e.g.Array.Sort(complexArray,(a,b)=>a.real.CompareTo(b.real));RegardsAndi
19 Jul 2016 by Member 12642406
I'm given this line of code in particular: public void Test8(List items, int places)The tasks for this problem is to come up with solution where I am able to rotate the List to the right by the specified number of places. A List rotation can be seen as circular, which means...
9 May 2017 by W Balboos, GHB
Your problem is rather obvious: the sort is perfect! You see date, the computer sees characters. You need to sort them either in your SQL query before you convert the datetime field to a string (unless you horribly store dates as strings!) or maybe try a more useful date format: YYYYMMDD...