<p>Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this?</p>

<pre><code>TExample = record
  SortOrder : integer;
  SomethingElse : string;
end;

var SomeVar : array of TExample;
</code></pre>

[{'answer_id': 41809, 'author': 'Ralph M. Rickenbach', 'author_id': 4549416, 'author_profile': 'https://Stackoverflow.com/users/4549416', 'pm_score': 0, 'selected': False, 'text': '<p>Use one of the sort alorithms propose by <a href="http://en.wikipedia.org/wiki/Sorting_algorithm" rel="nofollow noreferrer">Wikipedia</a>. The Swap function should swap array elements using a temporary variable of the same type as the array elements. Use a stable sort if you want entries with the same SortOrder integer value to stay in the order they were in the first place.</p>\n'}, {'answer_id': 41951, 'author': 'Barry Kelly', 'author_id': 3712, 'author_profile': 'https://Stackoverflow.com/users/3712', 'pm_score': 6, 'selected': True, 'text': "<p>You can add pointers to the elements of the array to a <code>TList</code>, then call <code>TList.Sort</code> with a comparison function, and finally create a new array and copy the values out of the TList in the desired order.</p>\n\n<p>However, if you're using the next version, D2009, there is a new collections library which can sort arrays. It takes an optional <code>IComparer&lt;TExample&gt;</code> implementation for custom sorting orders. Here it is in action for your specific case:</p>\n\n<pre><code>TArray.Sort&lt;TExample&gt;(SomeVar , TDelegatedComparer&lt;TExample&gt;.Construct(\n  function(const Left, Right: TExample): Integer\n  begin\n    Result := TComparer&lt;Integer&gt;.Default.Compare(Left.SortOrder, Right.SortOrder);\n  end));\n</code></pre>\n"}, {'answer_id': 49702, 'author': 'ddowns', 'author_id': 5201, 'author_profile': 'https://Stackoverflow.com/users/5201', 'pm_score': 1, 'selected': False, 'text': '<p>With an array, I\'d use either <code>quicksort</code> or possibly <code>heapsort</code>, and just change the comparison to use <code>TExample.SortOrder</code>, the swap part is still going to just act on the array and swap pointers. If the array is very large then you may want a linked list structure if there\'s a lot of insertion and deletion.</p>\n\n<p>C based routines, there are several here\n<a href="http://www.yendor.com/programming/sort/" rel="nofollow noreferrer">http://www.yendor.com/programming/sort/</a></p>\n\n<p>Another site, but has pascal source\n<a href="http://www.dcc.uchile.cl/~rbaeza/handbook/sort_a.html" rel="nofollow noreferrer">http://www.dcc.uchile.cl/~rbaeza/handbook/sort_a.html</a></p>\n'}, {'answer_id': 161661, 'author': 'CoolMagic', 'author_id': 22641, 'author_profile': 'https://Stackoverflow.com/users/22641', 'pm_score': 2, 'selected': False, 'text': '<p>If your need sorted by string then use sorted <code>TStringList</code> and \nadd record by <code>TString.AddObject(string, Pointer(int_val))</code>.</p>\n\n<p>But If need sort by integer field and string - use <code>TObjectList</code> and after adding all records call <code>TObjectList.Sort</code> with necessary sorted functions as parameter.</p>\n'}, {'answer_id': 161880, 'author': 'Germán Estévez -Neftalí-', 'author_id': 17487, 'author_profile': 'https://Stackoverflow.com/users/17487', 'pm_score': 0, 'selected': False, 'text': '<p><code>TStringList</code> have efficient Sort Method.<br>\nIf you want Sort use a <code>TStringList</code> object with <code>Sorted</code> property to True.  </p>\n\n<p>NOTE: For more speed, add objects in a not Sorted <code>TStringList</code> and at the end change the property to True.<br>\nNOTE: For sort by integer Field, convert to String.<br>\nNOTE: If there are duplicate values, this method not is Valid.   </p>\n\n<p>Regards.</p>\n'}, {'answer_id': 162850, 'author': 'skamradt', 'author_id': 9217, 'author_profile': 'https://Stackoverflow.com/users/9217', 'pm_score': 2, 'selected': False, 'text': '<p>This all depends on the number of records you are sorting.  If you are only sorting less than a few hundred then the other sort methods work fine, if you are going to be sorting more, then take a good look at the old trusty Turbo Power <a href="http://sourceforge.net/projects/tpsystools/" rel="nofollow noreferrer">SysTools</a> project.  There is a very good sort algorithm included in the source.  One that does a very good job sorting millions of records in a efficient manner.</p>\n\n<p>If you are going to use the tStringList method of sorting a list of records, make sure that your integer is padded to the right before inserting it into the list.  You can use the <strong>format(\'%.10d\',[rec.sortorder])</strong> to right align to 10 digits for example.</p>\n'}, {'answer_id': 1381865, 'author': 'Guy Gordon', 'author_id': 652328, 'author_profile': 'https://Stackoverflow.com/users/652328', 'pm_score': 4, 'selected': False, 'text': "<p>(I know this is a year later, but still useful stuff.)</p>\n<p>Skamradt's suggestion to pad integer values assumes you are going to sort using a string compare.  This would be slow.  Calling format() for each insert, slower still.  Instead, you want to do an integer compare.</p>\n<p>You start with a record type:</p>\n<pre><code>TExample = record\n  SortOrder : integer;\n  SomethingElse : string;\nend;\n</code></pre>\n<p>You didn't state how the records were stored, or how you wanted to access them once sorted.  So let's assume you put them in a Dynamic Array:</p>\n<pre><code>var MyDA:  Array of TExample; \n...\n  SetLength(MyDA,NewSize);           //allocate memory for the dynamic array\n  for i:=0 to NewSize-1 do begin        //fill the array with records\n    MyDA[i].SortOrder := SomeInteger;\n    MyDA[i].SomethingElse := SomeString;\n  end;\n</code></pre>\n<p>Now you want to sort this array by the integer value SortOrder.  If what you want out is a TStringList (so you can use the ts.Find method) then you should add each string to the list and add the SortOrder as a pointer.  Then sort on the pointer:</p>\n<pre><code>var  tsExamples: TStringList;         //declare it somewhere (global or local)\n...\n  tsExamples := tStringList.create;   //allocate it somewhere (and free it later!)\n...\n  tsExamples.Clear;                   //now let's use it\n  tsExamples.sorted := False;         //don't want to sort after every add\n  tsExamples.Capacity := High(MyDA)+1; //don't want to increase size with every add\n                                      //an empty dynamic array has High() = -1\n  for i:=0 to High(MyDA) do begin\n    tsExamples.AddObject(MyDA[i].SomethingElse,TObject(MyDA[i].SortOrder));\n  end;\n</code></pre>\n<p>Note the trick of casting the Integer SortOrder into a TObject pointer, which is stored in the TStringList.Object property.  (This depends upon the fact that Integer and Pointer are the same size.)  Somewhere we must define a function to compare the TObject pointers:</p>\n<pre><code>function CompareObjects(ts:tStringList; Item1,Item2: integer): Integer;\nbegin\n  Result := CompareValue(Integer(ts.Objects[Item1]), Integer(ts.Objects[Item2]))\nend;\n</code></pre>\n<p>Now, we can sort the tsList on .Object by calling .CustomSort instead of .Sort (which would sort on the string value.)</p>\n<pre><code>tsExamples.CustomSort(@CompareObjects);     //Sort the list\n</code></pre>\n<p>The TStringList is now sorted, so you can iterate over it from 0 to .Count-1 and read the strings in sorted order.</p>\n<p>But suppose you didn't want a TStringList, just an array in sorted order.  Or the records contain more data than just the one string in this example, and your sort order is more complex.  You can skip the step of adding every string, and just add the array index as Items in a TList.  Do everything above the same way, except use a TList instead of TStringList:</p>\n<pre><code>var Mlist: TList;                 //a list of Pointers\n...\n  for i:=0 to High(MyDA) do\n    Mlist.add(Pointer(i));        //cast the array index as a Pointer\n  Mlist.Sort(@CompareRecords);    //using the compare function below\n\nfunction CompareRecords(Item1, Item2: Integer): Integer;\nvar i,j: integer;\nbegin\n  i := integer(item1);            //recover the index into MyDA\n  j := integer(item2);            // and use it to access any field\n  Result := SomeFunctionOf(MyDA[i].SomeField) - SomeFunctionOf(MyDA[j].SomeField);\nend;\n</code></pre>\n<p>Now that Mlist is sorted, use it as a lookup table to access the array in sorted order:</p>\n<pre><code>  for i:=0 to Mlist.Count-1 do begin\n    Something := MyDA[integer(Mlist[i])].SomeField;\n  end;\n</code></pre>\n<p>As i iterates over the TList, we get back the array indexes in sorted order.  We just need to cast them back to integers, since the TList thinks they're pointers.</p>\n<p>I like doing it this way, but you could also put real pointers to array elements in the TList by adding the Address of the array element instead of it's index.  Then to use them you would cast them as pointers to TExample records.  This is what Barry Kelly and CoolMagic said to do in their answers.</p>\n"}, {'answer_id': 9001207, 'author': 'rt15', 'author_id': 1168949, 'author_profile': 'https://Stackoverflow.com/users/1168949', 'pm_score': 1, 'selected': False, 'text': '<p>The quicksort algorithm is often used when fast sorting is required. Delphi is (Or was) using it for List.Sort for example.\nDelphi List can be used to sort anything, but it is an heavyweight container, which is supposed to look like an array of pointers on structures. It is heavyweight even if we use tricks like Guy Gordon in this thread (Putting index or anything in place of pointers, or putting directly values if they are smaller than 32 bits): we need to construct a list and so on...</p>\n\n<p>Consequently, an alternative to easily and fastly sort an array of struct might be to use <a href="http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/" rel="nofollow">qsort C runtime function</a> from msvcrt.dll.</p>\n\n<p>Here is a declaration that might be good (Warning: code portable on windows only).</p>\n\n<pre><code>type TComparatorFunction = function(lpItem1: Pointer; lpItem2: Pointer): Integer; cdecl;\nprocedure qsort(base: Pointer; num: Cardinal; size: Cardinal; lpComparatorFunction: TComparatorFunction) cdecl; external \'msvcrt.dll\';\n</code></pre>\n\n<p>Full example <a href="http://www.delphifr.com/forum/sujet-COLOR-IMAGE_1567766.aspx#3" rel="nofollow">here</a>.</p>\n\n<p>Notice that directly sorting the array of records can be slow if the records are big. In that case, sorting an array of pointer to the records can be faster (Somehow like List approach).</p>\n'}, {'answer_id': 28460112, 'author': 'David Miró', 'author_id': 2270217, 'author_profile': 'https://Stackoverflow.com/users/2270217', 'pm_score': -1, 'selected': False, 'text': "<p>I created a very simple example that works correctly if the sort field is a string.</p>\n\n<pre><code>Type\n  THuman = Class\n  Public\n    Name: String;\n    Age: Byte;\n    Constructor Create(Name: String; Age: Integer);\n  End;\n\nConstructor THuman.Create(Name: String; Age: Integer);\nBegin\n  Self.Name:= Name;\n  Self.Age:= Age;\nEnd;\n\nProcedure Test();\nVar\n Human: THuman;\n Humans: Array Of THuman;\n List: TStringList;\nBegin\n\n SetLength(Humans, 3);\n Humans[0]:= THuman.Create('David', 41);\n Humans[1]:= THuman.Create('Brian', 50);\n Humans[2]:= THuman.Create('Alex', 20);\n\n List:= TStringList.Create;\n List.AddObject(Humans[0].Name, TObject(Humans[0]));\n List.AddObject(Humans[1].Name, TObject(Humans[1]));\n List.AddObject(Humans[2].Name, TObject(Humans[2]));\n List.Sort;\n\n Human:= THuman(List.Objects[0]);\n Showmessage('The first person on the list is the human ' + Human.name + '!');\n\n List.Free;\nEnd;\n</code></pre>\n"}, {'answer_id': 47884859, 'author': 'Jacek Krawczyk', 'author_id': 1960514, 'author_profile': 'https://Stackoverflow.com/users/1960514', 'pm_score': 0, 'selected': False, 'text': '<p>If you have Delphi XE2 or newer, you can try:</p>\n\n<pre><code>var \n  someVar: array of TExample;\n  list: TList&lt;TExample&gt;;\n  sortedVar: array of TExample;\nbegin\n  list := TList&lt;TExample&gt;.Create(someVar);\n  try\n    list.Sort;\n    sortedVar := list.ToArray;\n  finally\n    list.Free;\n  end;\nend;\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/41733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1008/']