
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


Task

Sort an array (or list) of integers in ascending numerical order.



Use a sorting facility provided by the language/library if possible.




' version 11-03-2016
' compile with: fbc -s console
 
#Include Once "crt/stdlib.bi"      ' needed for qsort subroutine
 
' Declare Sub qsort (ByVal As Any Ptr, <== point to start of array
'                    ByVal As size_t,  <== size of array
'                    ByVal As size_t,  <== size of array element
' ByVal As Function(ByVal As Any Ptr, ByVal As Any Ptr) As Long)  <== callback function
' declare callback function with Cdecl to ensures that the parameters are passed in the correct order
'
' size of long: 4 bytes on 32bit OS, 8 bytes on 64bit OS
 
' ascending
 Function callback Cdecl (ByVal element1 As Any Ptr, ByVal element2 As Any Ptr) As Long
     Function = *Cast(Long Ptr, element1) - *Cast(Long Ptr, element2)
End Function
 
' Function callback Cdecl (ByVal element1 As Any Ptr, ByVal element2 As Any Ptr) As Long
' Dim As Long e1 = *Cast(Long Ptr, element1)
' Dim As Long e2 = *Cast(Long Ptr, element2)
' Dim As Long result = Sgn(e1 - e2)
' If Sgn(e1) = -1 And Sgn(e2) = -1 Then result = -result
'     Function = result
' End Function
 
' ------=< MAIN >=------
 
Dim As Long i, array(20)
 
Dim As Long lb = LBound(array)
Dim As Long ub = UBound(array)
 
For i = lb To ub     ' fill array
    array(i) = 10 - i
Next
 
Print
Print "unsorted array"
For i = lb To ub     ' display array
    Print Using "###";array(i);
Next
Print : Print
 
' sort array
qsort(@array(lb), ub - lb +1, SizeOf(array), @callback)
 
Print "sorted array"
For i = lb To ub     ' show sorted array
    Print Using "###";array(i);
Next
Print
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End