
Sorting Algorithm

This is a sorting algorithm.   It may be applied to a set of data in order to sort it.    
For comparing various sorts, see compare sorts.  
For other sorting algorithms,   see sorting algorithms,   or:

O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort


Sort an array of composite structures by a key.



For example, if you define a composite structure that presents a name-value pair (in pseudo-code):

Define structure pair such that: 
   name as a string
   value as a string

and an array of such pairs:

   x: array of pairs

then define a sort routine that sorts the array x by the key name.

This task can always be accomplished with Sorting Using a Custom Comparator.

If your language is not listed here, please see the other article.




' FB 1.05.0 Win64
 
Type Pair
  As String name, value
  Declare Constructor(name_ As String, value_ As String)
  Declare Operator Cast() As String
End Type
 
Constructor Pair(name_ As String, value_ As String)
  name  = name_
  value = value_
End Constructor
 
Operator Pair.Cast() As String
  Return "[" + name + ", " + value + "]"
End Operator
 
' selection sort, quick enough for sorting small number of pairs
Sub sortPairsByName(p() As Pair)
  Dim As Integer i, j, m
  For i = LBound(p) To UBound(p) - 1
    m = i
    For j = i + 1 To UBound(p)
      If p(j).name < p(m).name Then m = j
    Next j
    If m <> i Then Swap p(i), p(m)
  Next i
End Sub
 
Dim As Pair pairs(1 To 4) = _
{ _
  Pair("grass", "green"), _ 
  Pair("snow", "white" ), _
  Pair("sky", "blue"),    _
  Pair("cherry", "red")   _
}
 
Print "Before sorting :"
For i As Integer = 1 To 4
  Print Tab(3); pairs(i)
Next
 
sortPairsByName pairs()
 
Print
Print "After sorting by name :"
For i As Integer = 1 To 4
  Print Tab(3); pairs(i)
Next
 
Print
Print "Press any key to quit"
Sleep