task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
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 of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#COBOL
COBOL
>>SOURCE FORMAT FREE *> This code is dedicated to the public domain *> This is GNUCOBOL 2.0 identification division. program-id. beadsort. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 01 filler. 03 row occurs 9 pic x(9). 03 r pic 99. 03 r1 pic 99. 03 r2 pic 99. 03 pole pic 99. 03 a-lim pic 99 value 9. 03 a pic 99. 03 array occurs 9 pic 9. 01 NL pic x value x'0A'. procedure division. start-beadsort.   *> fill the array compute a = random(seconds-past-midnight) perform varying a from 1 by 1 until a > a-lim compute array(a) = random() * 10 end-perform   perform display-array display space 'initial array'   *> distribute the beads perform varying r from 1 by 1 until r > a-lim move all '.' to row(r) perform varying pole from 1 by 1 until pole > array(r) move 'o' to row(r)(pole:1) end-perform end-perform display NL 'initial beads' perform display-beads   *> drop the beads perform varying pole from 1 by 1 until pole > a-lim move a-lim to r2 perform find-opening compute r1 = r2 - 1 perform find-bead perform until r1 = 0 *> no bead or no opening *> drop the bead move '.' to row(r1)(pole:1) move 'o' to row(r2)(pole:1) *> continue up the pole compute r2 = r2 - 1 perform find-opening compute r1 = r2 - 1 perform find-bead end-perform end-perform display NL 'dropped beads' perform display-beads   *> count the beads in each row perform varying r from 1 by 1 until r > a-lim move 0 to array(r) inspect row(r) tallying array(r) for all 'o' before initial '.' end-perform   perform display-array display space 'sorted array'   stop run . find-opening. perform varying r2 from r2 by -1 until r2 = 1 or row(r2)(pole:1) = '.' continue end-perform . find-bead. perform varying r1 from r1 by -1 until r1 = 0 or row(r1)(pole:1) = 'o' continue end-perform . display-array. display space perform varying a from 1 by 1 until a > a-lim display space array(a) with no advancing end-perform . display-beads. perform varying r from 1 by 1 until r > a-lim display row(r) end-perform . end program beadsort.
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
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 This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#BBC_BASIC
BBC BASIC
DEF PROC_ShakerSort(Size%)   Start%=2 End%=Size% Direction%=1 LastChange%=1 REPEAT FOR J% = Start% TO End% STEP Direction% IF data%(J%-1) > data%(J%) THEN SWAP data%(J%-1),data%(J%) LastChange% = J% ENDIF NEXT J% End% = Start% Start% = LastChange% - Direction% Direction% = Direction% * -1 UNTIL ( ( End% * Direction% ) < ( Start% * Direction% ) )   ENDPROC
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
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 This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Groovy
Groovy
def countingSort = { array -> def max = array.max() def min = array.min() // this list size allows use of Groovy's natural negative indexing def count = [0] * (max + 1 + [0, -min].max()) array.each { count[it] ++ } (min..max).findAll{ count[it] }.collect{ [it]*count[it] }.flatten() }
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program customSort64.s */   /* use merge sort iteratif and pointer table */ /* but use a extra table on stack for the merge */ /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*******************************************/ /* Structures */ /********************************************/ /* city structure */ .struct 0 city_name: // .struct city_name + 8 // string pointer city_country: // .struct city_country + 8 // string pointer city_end:   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .asciz "Name : @ country : @ \n" szMessSortName: .asciz "Ascending sort table for name of city :\n" szMessSortCitiesDesc: .asciz "Descending sort table for name of city : \n" szCarriageReturn: .asciz "\n"   // cities name szLondon: .asciz "London" szNewyork: .asciz "New York" szBirmin: .asciz "Birmingham" szParis: .asciz "Paris" // country name szUK: .asciz "UK" szUS: .asciz "US" szFR: .asciz "FR" .align 4 TableCities: e1: .quad szLondon // address name string .quad szUK // address country string e2: .quad szParis .quad szFR e3: .quad szNewyork .quad szUS e4: .quad szBirmin .quad szUK e5: .quad szParis .quad szUS e6: .quad szBirmin .quad szUS /* pointers table */ ptrTableCities: .quad e1 .quad e2 .quad e3 .quad e4 .quad e5 .quad e6 .equ NBELEMENTS, (. - ptrTableCities) / 8   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x0,qAdrptrTableCities // address pointers table bl displayTable   ldr x0,qAdrszMessSortName bl affichageMess   ldr x0,qAdrptrTableCities // address pointers table mov x1,0 // first element mov x2,NBELEMENTS // number of élements adr x3,comparAreaAlphaCrois // address custom comparator ascending bl mergeSortIter ldr x0,qAdrptrTableCities // address table bl displayTable   ldr x0,qAdrszMessSortCitiesDesc bl affichageMess   ldr x0,qAdrptrTableCities // address table mov x1,0 // first element mov x2,NBELEMENTS // number of élements adr x3,comparAreaAlphaDecrois // address custom comparator descending bl mergeSortIter ldr x0,qAdrptrTableCities // address table bl displayTable   100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrsZoneConv: .quad sZoneConv qAdrszCarriageReturn: .quad szCarriageReturn qAdrsMessResult: .quad sMessResult qAdrTableCities: .quad TableCities qAdrszMessSortName: .quad szMessSortName qAdrszMessSortCitiesDesc: .quad szMessSortCitiesDesc qAdrptrTableCities: .quad ptrTableCities   /******************************************************************/ /* merge sort iteratif */ /* use an extra table on stack */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the index of first element */ /* x2 contains the number of element */ /* x3 contains the address of custom comparator */ mergeSortIter: stp fp,lr,[sp,-16]! // save registers stp x1,x2,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers stp x8,x9,[sp,-16]! // save registers stp x10,x11,[sp,-16]! // save registers stp x12,x13,[sp,-16]! // save registers stp x14,x15,[sp,-16]! // save registers mov x15,x0 // save address mov x4,x1 // save N0 first element sub x5,x2,1 // save N° last element tst x2,1 // number of element odd ? add x13,x2,1 // yes then add 1 csel x13,x13,x2,ne // to have a multiple to 16 bytes lsl x13,x13,3 // for reserve the extra table to the stack sub sp,sp,x13 mov fp,sp // frame register = address extra table on stack   mov x10,1 // subset size 1: mov x6,x4 // first element 2: lsl x8,x10,1 // compute end subset add x8,x8,x6 sub x8,x8,1 add x7,x6,x8 // compute median lsr x7,x7,1 cmp x8,x5 // maxi ? ble 21f // no mov x8,x5 // yes -> end subset = maxi cmp x6,0 // subset final ? beq 21f // no cmp x7,x8 // compare median end subset blt 21f mov x7,x8 // maxi -> median   21: add x9,x7,1 mov x0,x15 3: // copy first subset on extra table sub x1,x9,1 ldr x2,[x0,x1,lsl 3] str x2,[fp,x1,lsl 3] sub x9,x9,1 cmp x9,x6 bgt 3b mov x9,x7 cmp x7,x8 beq 41f 4: // and copy inverse second subset on extra table add x1,x9,1 add x12,x7,x8 sub x12,x12,x9 ldr x2,[x0,x1,lsl 3] str x2,[fp,x12,lsl 3] add x9,x9,1 cmp x9,x8 blt 4b 41: mov x11,x6 //k mov x1,x6 // i mov x2,x8 // j 5: // and now merge the two subset on final table mov x0,fp blr x3 cmp x0,0 bgt 7f blt 6f // si egalité et si i < pivot cmp x1,x7 ble 6f b 7f 6: ldr x12,[fp,x1, lsl 3] str x12,[x15,x11, lsl 3] add x1,x1,1 b 8f 7: ldr x12,[fp,x2, lsl 3] str x12,[x15,x11, lsl 3] sub x2,x2,1 8: add x11,x11,1 cmp x11,x8 ble 5b   9: mov x0,x15 lsl x2,x10,1 add x6,x6,x2 // compute new subset cmp x6,x5 // end ? ble 2b lsl x10,x10,1 // size of subset * 2 cmp x10,x5 // end ? ble 1b   100: add sp,sp,x13 // stack alignement ldp x14,x15,[sp],16 // restaur 2 registers ldp x12,x13,[sp],16 // restaur 2 registers ldp x10,x11,[sp],16 // restaur 2 registers ldp x8,x9,[sp],16 // restaur 2 registers ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x1,x2,[sp],16 // restaur 2 registers ldp fp,lr,[sp],16 // restaur 2 registers ret // return to address lr x30   /******************************************************************/ /* ascending comparison sort area */ /******************************************************************/ /* x0 contains the address of table */ /* x1 indice area sort 1 */ /* x2 indice area sort 2 */ comparAreaAlphaCrois: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers stp x8,x9,[sp,-16]! // save registers   ldr x1,[x0,x1,lsl 3] // load pointer element 1 ldr x6,[x1,city_name] // load area sort element 1 ldr x2,[x0,x2,lsl 3] // load pointer element 2 ldr x7,[x2,city_name] // load area sort element 2   mov x8,#0 // compar alpha string 1: ldrb w9,[x6,x8] // byte string 1 ldrb w5,[x7,x8] // byte string 2 cmp w9,w5 bgt 11f // croissant blt 10f   cmp w9,#0 // end string 1 beq 12f // end comparaison add x8,x8,#1 // else add 1 in counter b 1b // and loop   10: // lower mov x0,-1 b 100f 11: // highter mov x0,1 b 100f 12: // equal mov x0,0 100: ldp x8,x9,[sp],16 // restaur 2 registers ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* descending comparison sort area */ /******************************************************************/ /* x0 contains the address of table */ /* x1 indice area sort 1 */ /* x2 indice area sort 2 */ comparAreaAlphaDecrois: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers stp x8,x9,[sp,-16]! // save registers   ldr x1,[x0,x1,lsl 3] // load pointer element 1 ldr x6,[x1,city_name] // load area sort element 1 ldr x2,[x0,x2,lsl 3] // load pointer element 2 ldr x7,[x2,city_name] // load area sort element 2   mov x8,#0 // compar alpha string 1: ldrb w9,[x6,x8] // byte string 1 ldrb w5,[x7,x8] // byte string 2 cmp w9,w5 blt 11f // descending bgt 10f   cmp w9,#0 // end string 1 beq 12f // end comparaison add x8,x8,#1 // else add 1 in counter b 1b // and loop   10: // lower mov x0,-1 b 100f 11: // highter mov x0,1 b 100f 12: // equal mov x0,0 100: ldp x8,x9,[sp],16 // restaur 2 registers ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* Display table elements */ /******************************************************************/ /* x0 contains the address of table */ displayTable: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers mov x2,x0 // table address mov x3,0 1: // loop display table lsl x4,x3,#3 // offset element ldr x6,[x2,x4] // load pointer ldr x1,[x6,city_name] ldr x0,qAdrsMessResult bl strInsertAtCharInc // put name in message ldr x1,[x6,city_country] // and put country in the message bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message add x3,x3,1 cmp x3,#NBELEMENTS blt 1b ldr x0,qAdrszCarriageReturn bl affichageMess 100: ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Action.21
Action!
DEFINE PTR="CARD"   PROC PrintArray(PTR ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI Print(a(i)) OD Put(']) PutE() RETURN   INT FUNC CustomComparator(CHAR ARRAY s1,s2) INT res   res=s2(0) res==-s1(0) IF res=0 THEN res=SCompare(s1,s2) FI RETURN (res)   INT FUNC Comparator=*(CHAR ARRAY s1,s2) DEFINE JSR="$20" DEFINE RTS="$60" [JSR $00 $00 ;JSR to address set by SetComparator RTS]   PROC SetComparator(PTR p) PTR addr   addr=Comparator+1 ;location of address of JSR PokeC(addr,p) RETURN   PROC InsertionSort(PTR ARRAY a INT size PTR compareFun) INT i,j CHAR ARRAY s   SetComparator(compareFun) FOR i=1 TO size-1 DO s=a(i) j=i-1 WHILE j>=0 AND Comparator(s,a(j))<0 DO a(j+1)=a(j) j==-1 OD a(j+1)=s OD RETURN   PROC Test(PTR ARRAY a INT size PTR compareFun) PrintE("Array before sort:") PrintArray(a,size) PutE()   InsertionSort(a,size,compareFun) PrintE("Array after sort:") PrintArray(a,size) PutE() RETURN   PROC Main() PTR ARRAY a(24)   a(0)="lorem" a(1)="ipsum" a(2)="dolor" a(3)="sit" a(4)="amet" a(5)="consectetur" a(6)="adipiscing" a(7)="elit" a(8)="maecenas" a(9)="varius" a(10)="sapien" a(11)="vel" a(12)="purus" a(13)="hendrerit" a(14)="vehicula" a(15)="integer" a(16)="hendrerit" a(17)="viverra" a(18)="turpis" a(19)="ac" a(20)="sagittis" a(21)="arcu" a(22)="pharetra" a(23)="id"   Test(a,24,CustomComparator) RETURN
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#Kotlin
Kotlin
// version 1.1.2   fun <T : Comparable<T>> combSort(input: Array<T>) { var gap = input.size if (gap <= 1) return // already sorted var swaps = false while (gap > 1 || swaps) { gap = (gap / 1.247331).toInt() if (gap < 1) gap = 1 var i = 0 swaps = false while (i + gap < input.size) { if (input[i] > input[i + gap]) { val tmp = input[i] input[i] = input[i + gap] input[i + gap] = tmp swaps = true } i++ } } }   fun main(args: Array<String>) { val ia = arrayOf(28, 44, 46, 24, 19, 2, 17, 11, 25, 4) println("Unsorted : ${ia.contentToString()}") combSort(ia) println("Sorted  : ${ia.contentToString()}") println() val ca = arrayOf('X', 'B', 'E', 'A', 'Z', 'M', 'S', 'L', 'Y', 'C') println("Unsorted : ${ca.contentToString()}") combSort(ca) println("Sorted  : ${ca.contentToString()}") }
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Haskell
Haskell
import System.Random import Data.Array.IO import Control.Monad   isSortedBy :: (a -> a -> Bool) -> [a] -> Bool isSortedBy _ [] = True isSortedBy f xs = all (uncurry f) . (zip <*> tail) $ xs     -- from http://www.haskell.org/haskellwiki/Random_shuffle shuffle :: [a] -> IO [a] shuffle xs = do ar <- newArray n xs forM [1..n] $ \i -> do j <- randomRIO (i,n) vi <- readArray ar i vj <- readArray ar j writeArray ar j vi return vj where n = length xs newArray :: Int -> [a] -> IO (IOArray Int a) newArray n xs = newListArray (1,n) xs   bogosortBy :: (a -> a -> Bool) -> [a] -> IO [a] bogosortBy f xs | isSortedBy f xs = return xs | otherwise = shuffle xs >>= bogosortBy f   bogosort :: Ord a => [a] -> IO [a] bogosort = bogosortBy (<)
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
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 A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Action.21
Action!
PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   PROC BubbleSort(INT ARRAY a INT size) INT count,changed,i,tmp   count=size IF count<=1 THEN RETURN FI   DO changed=0 count==-1 FOR i=0 TO count-1 DO IF a(i)>a(i+1) THEN tmp=a(i) a(i)=a(i+1) a(i+1)=tmp changed=1 FI OD UNTIL changed=0 OD RETURN   PROC Test(INT ARRAY a INT size) PrintE("Array before sort:") PrintArray(a,size) BubbleSort(a,size) PrintE("Array after sort:") PrintArray(a,size) PutE() RETURN   PROC Main() INT ARRAY a(10)=[1 4 65535 0 3 7 4 8 20 65530], b(21)=[10 9 8 7 6 5 4 3 2 1 0 65535 65534 65533 65532 65531 65530 65529 65528 65527 65526], c(8)=[101 102 103 104 105 106 107 108], d(12)=[1 65535 1 65535 1 65535 1 65535 1 65535 1 65535]   Test(a,10) Test(b,21) Test(c,8) Test(d,12) RETURN
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
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 This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#E
E
def gnomeSort(array) { var size := array.size() var i := 1 var j := 2 while (i < size) { if (array[i-1] <= array[i]) { i := j j += 1 } else { def t := array[i-1] array[i-1] := array[i] array[i] := t i -= 1 if (i <=> 0) { i := j j += 1 } } } }
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
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 of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Common_Lisp
Common Lisp
  (defun transpose (remain &optional (ret '())) (if (null remain) ret (transpose (remove-if #'null (mapcar #'cdr remain)) (append ret (list (mapcar #'car remain))))))   (defun bead-sort (xs) (mapcar #'length (transpose (transpose (mapcar (lambda (x) (make-list x :initial-element 1)) xs)))))   (bead-sort '(5 2 4 1 3 3 9))  
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
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 This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#C
C
#include <stdio.h>   // can be any swap function. This swap is optimized for numbers. void swap(int *x, int *y) { if(x == y) return; *x ^= *y; *y ^= *x; *x ^= *y; } void cocktailsort(int *a, size_t n) { while(1) { // packing two similar loops into one char flag; size_t start[2] = {1, n - 1}, end[2] = {n, 0}, inc[2] = {1, -1}; for(int it = 0; it < 2; ++it) { flag = 1; for(int i = start[it]; i != end[it]; i += inc[it]) if(a[i - 1] > a[i]) { swap(a + i - 1, a + i); flag = 0; } if(flag) return; } } }   int main(void) { int a[] = { 5, -1, 101, -4, 0, 1, 8, 6, 2, 3 }; size_t n = sizeof(a)/sizeof(a[0]);   cocktailsort(a, n); for (size_t i = 0; i < n; ++i) printf("%d ", a[i]); return 0; }
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
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 This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Haskell
Haskell
import Data.Array   countingSort :: (Ix n) => [n] -> n -> n -> [n] countingSort l lo hi = concatMap (uncurry $ flip replicate) count where count = assocs . accumArray (+) 0 (lo, hi) . map (\i -> (i, 1)) $ l
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Ada
Ada
  with Ada.Text_Io; use Ada.Text_Io; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Gnat.Heap_Sort_G;   procedure Custom_Compare is   type StringArrayType is array (Natural range <>) of Unbounded_String;   Strings : StringArrayType := (Null_Unbounded_String, To_Unbounded_String("this"), To_Unbounded_String("is"), To_Unbounded_String("a"), To_Unbounded_String("set"), To_Unbounded_String("of"), To_Unbounded_String("strings"), To_Unbounded_String("to"), To_Unbounded_String("sort"), To_Unbounded_String("This"), To_Unbounded_String("Is"), To_Unbounded_String("A"), To_Unbounded_String("Set"), To_Unbounded_String("Of"), To_Unbounded_String("Strings"), To_Unbounded_String("To"), To_Unbounded_String("Sort"));   procedure Move (From, To : in Natural) is   begin Strings(To) := Strings(From); end Move;   function UpCase (Char : in Character) return Character is Temp : Character; begin if Char >= 'a' and Char <= 'z' then Temp := Character'Val(Character'Pos(Char) - Character'Pos('a') + Character'Pos('A')); else Temp := Char; end if; return Temp; end UpCase;   function Lt (Op1, Op2 : Natural) return Boolean is Temp, Len : Natural; begin Len := Length(Strings(Op1)); Temp := Length(Strings(Op2)); if Len < Temp then return False; elsif Len > Temp then return True; end if;   declare S1, S2 : String(1..Len); begin S1 := To_String(Strings(Op1)); S2 := To_String(Strings(Op2)); Put("Same size: "); Put(S1); Put(" "); Put(S2); Put(" "); for I in S1'Range loop Put(UpCase(S1(I))); Put(UpCase(S2(I))); if UpCase(S1(I)) = UpCase(S2(I)) then null; elsif UpCase(S1(I)) < UpCase(S2(I)) then Put(" LT"); New_Line; return True; else return False; end if; end loop; Put(" GTE"); New_Line; return False; end; end Lt;   procedure Put (Arr : in StringArrayType) is begin for I in 1..Arr'Length-1 loop Put(To_String(Arr(I))); New_Line; end loop; end Put;   package Heap is new Gnat.Heap_Sort_G(Move, Lt); use Heap;     begin Put_Line("Unsorted list:"); Put(Strings); New_Line; Sort(16); New_Line; Put_Line("Sorted list:"); Put(Strings); end Custom_Compare;
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#Liberty_BASIC
Liberty BASIC
  'randomize 0.5 itemCount = 20 dim item(itemCount) for i = 1 to itemCount item(i) = int(rnd(1) * 100) next i print "Before Sort" for i = 1 to itemCount print item(i) next i print: print 't0=time$("ms")   gap=itemCount while gap>1 or swaps <> 0 gap=int(gap/1.25) 'if gap = 10 or gap = 9 then gap = 11 'uncomment to get Combsort11 if gap <1 then gap = 1 i = 1 swaps = 0 for i = 1 to itemCount-gap if item(i) > item(i + gap) then temp = item(i) item(i) = item(i + gap) item(i + gap) = temp swaps = 1 end if next wend   print "After Sort" 't1=time$("ms") 'print t1-t0   for i = 1 to itemCount print item(i) next i end  
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Icon_and_Unicon
Icon and Unicon
procedure shuffle(l) repeat { !l :=: ?l suspend l } end   procedure sorted(l) local i if (i := 2 to *l & l[i] >= l[i-1]) then return &fail else return 1 end   procedure main() local l l := [6,3,4,5,1] |( shuffle(l) & sorted(l)) \1 & every writes(" ",!l) end
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
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 A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#ActionScript
ActionScript
public function bubbleSort(toSort:Array):Array { var changed:Boolean = false;   while (!changed) { changed = true;   for (var i:int = 0; i < toSort.length - 1; i++) { if (toSort[i] > toSort[i + 1]) { var tmp:int = toSort[i]; toSort[i] = toSort[i + 1]; toSort[i + 1] = tmp;   changed = false; } } }   return toSort; }
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
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 This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Eiffel
Eiffel
  class GNOME_SORT [G -> COMPARABLE]   feature   sort (ar: ARRAY [G]): ARRAY [G] -- Sorted array in ascending order. require array_not_void: ar /= Void local i, j: INTEGER ith: G do create Result.make_empty Result.deep_copy (ar) from i := 2 j := 3 until i > Result.count loop if Result [i - 1] <= Result [i] then i := j j := j + 1 else ith := Result [i - 1] Result [i - 1] := Result [i] Result [i] := ith i := i - 1 if i = 1 then i := j j := j + 1 end end end ensure Same_length: ar.count = Result.count Result_is_sorted: is_sorted (Result) end   feature {NONE}   is_sorted (ar: ARRAY [G]): BOOLEAN --- Is 'ar' sorted in ascending order? require ar_not_empty: ar.is_empty = False local i: INTEGER do Result := True from i := ar.lower until i = ar.upper loop if ar [i] > ar [i + 1] then Result := False end i := i + 1 end end   end    
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
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 of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#D
D
import std.stdio, std.algorithm, std.range, std.array, std.functional;   alias repeat0 = curry!(repeat, 0);   // Currenty std.range.transposed doesn't work. auto columns(R)(R m) pure /*nothrow*/ @safe /*@nogc*/ { return m .map!walkLength .reduce!max .iota .map!(i => m.filter!(s => s.length > i).walkLength.repeat0); }   auto beadSort(in uint[] data) pure /*nothrow @nogc*/ { return data.map!repeat0.columns.columns.map!walkLength; }   void main() { [5, 3, 1, 7, 4, 1, 1].beadSort.writeln; }
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
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 This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#C.23
C#
public static void cocktailSort(int[] A) { bool swapped; do { swapped = false; for (int i = 0; i <= A.Length - 2; i++) { if (A[i] > A[i + 1]) { //test whether the two elements are in the wrong order int temp = A[i]; A[i] = A[i + 1]; A[i + 1] = temp; swapped = true; } } if (!swapped) { //we can exit the outer loop here if no swaps occurred. break; } swapped = false; for (int i = A.Length - 2; i >= 0; i--) { if (A[i] > A[i + 1]) { int temp = A[i]; A[i] = A[i + 1]; A[i + 1] = temp; swapped = true; } } //if no elements have been swapped, then the list is sorted } while (swapped); }
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
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 This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Haxe
Haxe
class CountingSort { public static function sort(arr:Array<Int>) { var min = arr[0], max = arr[0]; for (i in 1...arr.length) { if (arr[i] < min) min = arr[i]; else if (arr[i] > max) max = arr[i]; }   var range = max - min + 1; var count = new Array<Int>(); count.resize(range * arr.length);   for (i in 0...range) count[i] = 0; for (i in 0...arr.length) count[arr[i] - min]++;   var z = 0; for (i in min...(max + 1)) { for (j in 0...count[i - min]) arr[z++] = i; } } }   class Main { static function main() { var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; Sys.println('Unsorted Integers: ' + integerArray); CountingSort.sort(integerArray); Sys.println('Sorted Integers: ' + integerArray); } }
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
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 This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Icon_and_Unicon
Icon and Unicon
procedure main() #: demonstrate various ways to sort a list and string write("Sorting Demo using ",image(countingsort)) writes(" on list : ") writex(UL) displaysort(countingsort,copy(UL)) end   procedure countingsort(X) #: return sorted list (integers only) local T,lower,upper   T := table(0) # hash table as sparse array lower := upper := X[1]   every x := !X do { if not ( integer(x) = x ) then runerr(x,101) # must be integer lower >:= x # minimum upper <:= x # maximum T[x] +:= 1 # record x's and duplicates }   every put(X := [],( 1 to T[i := lower to upper], i) ) # reconstitute with correct order and count return X end
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#11l
11l
V x = 77444 V y = -12 V z = 0 (x, y, z) = tuple_sorted((x, y, z)) print(x‘ ’y‘ ’z)   V xs = ‘lions, tigers, and’ V ys = ‘bears, oh my!’ V zs = ‘(from the "Wizard of OZ")’ (xs, ys, zs) = sorted([xs, ys, zs]) print(xs"\n"ys"\n"zs)
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#ALGOL_68
ALGOL 68
# define the MODE that will be sorted # MODE SITEM = STRING; #--- Swap function ---# PROC swap = (REF[]SITEM array, INT first, INT second) VOID: ( SITEM temp := array[first]; array[first] := array[second]; array[second]:= temp ); #--- Quick sort partition arg function with custom comparision function ---# PROC quick = (REF[]SITEM array, INT first, INT last, PROC(SITEM,SITEM)INT compare) VOID: ( INT smaller := first + 1, larger := last; SITEM pivot := array[first]; WHILE smaller <= larger DO WHILE compare(array[smaller], pivot) < 0 AND smaller < last DO smaller +:= 1 OD; WHILE compare( array[larger], pivot) > 0 AND larger > first DO larger -:= 1 OD; IF smaller < larger THEN swap(array, smaller, larger); smaller +:= 1; larger -:= 1 ELSE smaller +:= 1 FI OD; swap(array, first, larger); IF first < larger-1 THEN quick(array, first, larger-1, compare) FI; IF last > larger +1 THEN quick(array, larger+1, last, compare) FI ); #--- Quick sort array function with custom comparison function ---# PROC quicksort = (REF[]SITEM array, PROC(SITEM,SITEM)INT compare) VOID: ( IF UPB array > LWB array THEN quick(array, LWB array, UPB array, compare) FI ); #***************************************************************# main: ( OP LENGTH = (STRING a)INT: ( UPB a + 1 ) - LWB a; OP TOLOWER = (STRING a)STRING: BEGIN STRING result := a; FOR i FROM LWB result TO UPB result DO CHAR c = a[i]; IF c >= "A" AND c <= "Z" THEN result[i] := REPR ( ( ABS c - ABS "A" ) + ABS "a" ) FI OD; result END # TOLOWER # ; # custom comparison, descending sort on length # # if lengths are equal, sort lexicographically # PROC compare = (SITEM a, b)INT: IF INT a length = LENGTH a; INT b length = LENGTH b; a length < b length THEN # a is shorter than b # 1 ELIF a length > b length THEN # a is longer than b # -1 ELIF STRING lower a = TOLOWER a; STRING lower b = TOLOWER b; lower a < lower b THEN # lowercase a is before lowercase b # -1 ELIF lower a > lower b THEN # lowercase a is after lowercase b # 1 ELIF a > b THEN # a and b are equal ignoring case, # # but a is after b considering case # 1 ELIF a < b THEN # a and b are equal ignoring case, # # but a is before b considering case # -1 ELSE # the strings are equal # 0 FI # compare # ; []SITEM orig = ("Here", "are", "some", "sample", "strings", "to", "be", "sorted"); [LWB orig : UPB orig]SITEM a := orig; print(("Before:"));FOR i FROM LWB a TO UPB a DO print((" ",a[i])) OD; print((newline)); quicksort(a, compare); print(("After :"));FOR i FROM LWB a TO UPB a DO print((" ",a[i])) OD; print((newline)) )
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#Lua
Lua
function combsort(t) local gapd, gap, swaps = 1.2473, #t, 0 while gap + swaps > 1 do local k = 0 swaps = 0 if gap > 1 then gap = math.floor(gap / gapd) end for k = 1, #t - gap do if t[k] > t[k + gap] then t[k], t[k + gap], swaps = t[k + gap], t[k], swaps + 1 end end end return t end   print(unpack(combsort{3,5,1,2,7,4,8,3,6,4,1}))
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Inform_6
Inform 6
[ shuffle a n i j tmp; for(i = n - 1: i > 0: i--) { j = random(i + 1) - 1;   tmp = a->j; a->j = a->i; a->i = tmp; } ];   [ is_sorted a n i; for(i = 0: i < n - 1: i++) { if(a->i > a->(i + 1)) rfalse; }   rtrue; ];   [ bogosort a n; while(~~is_sorted(a, n)) { shuffle(a, n); } ];
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
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 A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Ada
Ada
generic type Element is private; with function "=" (E1, E2 : Element) return Boolean is <>; with function "<" (E1, E2 : Element) return Boolean is <>; type Index is (<>); type Arr is array (Index range <>) of Element; procedure Bubble_Sort (A : in out Arr);   procedure Bubble_Sort (A : in out Arr) is Finished : Boolean; Temp  : Element; begin loop Finished := True; for J in A'First .. Index'Pred (A'Last) loop if A (Index'Succ (J)) < A (J) then Finished := False; Temp := A (Index'Succ (J)); A (Index'Succ (J)) := A (J); A (J) := Temp; end if; end loop; exit when Finished; end loop; end Bubble_Sort;   -- Example of usage: with Ada.Text_IO; use Ada.Text_IO; with Bubble_Sort; procedure Main is type Arr is array (Positive range <>) of Integer; procedure Sort is new Bubble_Sort (Element => Integer, Index => Positive, Arr => Arr); A : Arr := (1, 3, 256, 0, 3, 4, -1); begin Sort (A); for J in A'Range loop Put (Integer'Image (A (J))); end loop; New_Line; end Main;
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
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 This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Elena
Elena
import extensions; import system'routines;   extension op { gnomeSort() { var list := self.clone(); int i := 1; int j := 2;   while (i < list.Length) { if (list[i-1]<=list[i]) { i := j; j += 1 } else { list.exchange(i-1,i); i -= 1; if (i==0) { i := 1; j := 2 } } };   ^ list } }   public program() { var list := new int[]{3, 9, 4, 6, 8, 1, 7, 2, 5};   console.printLine("before:", list.asEnumerable()); console.printLine("after :", list.gnomeSort().asEnumerable()) }
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
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 of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Delphi
Delphi
program BeadSortTest;   {$APPTYPE CONSOLE}   uses SysUtils;   procedure BeadSort(var a : array of integer); var i, j, max, sum : integer; beads : array of array of integer; begin max := a[Low(a)]; for i := Low(a) + 1 to High(a) do if a[i] > max then max := a[i];   SetLength(beads, High(a) - Low(a) + 1, max);   // mark the beads   for i := Low(a) to High(a) do for j := 0 to a[i] - 1 do beads[i, j] := 1;   for j := 0 to max - 1 do begin // count how many beads are on each post sum := 0; for i := Low(a) to High(a) do begin sum := sum + beads[i, j]; beads[i, j] := 0; end; //mark bottom sum beads for i := High(a) + 1 - sum to High(a) do beads[i, j] := 1; end;   for i := Low(a) to High(a) do begin j := 0; while (j < max) and (beads[i, j] <> 0) do inc(j); a[i] := j; end;   SetLength(beads, 0, 0); end;   const N = 8; var i : integer; x : array[1..N] of integer = (5, 3, 1, 7, 4, 1, 1, 20); begin for i := 1 to N do writeln(Format('x[%d] = %d', [i, x[i]]));   BeadSort(x);   for i := 1 to N do writeln(Format('x[%d] = %d', [i, x[i]]));   readln; end.
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
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 This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#C.2B.2B
C++
  #include <iostream> #include <windows.h>   const int EL_COUNT = 77, LLEN = 11;   class cocktailSort { public: void sort( int* arr, int len ) { bool notSorted = true; while( notSorted ) { notSorted = false; for( int a = 0; a < len - 1; a++ ) { if( arr[a] > arr[a + 1] ) { sSwap( arr[a], arr[a + 1] ); notSorted = true; } }   if( !notSorted ) break; notSorted = false;   for( int a = len - 1; a > 0; a-- ) { if( arr[a - 1] > arr[a] ) { sSwap( arr[a], arr[a - 1] ); notSorted = true; } } } }   private: void sSwap( int& a, int& b ) { int t = a; a = b; b = t; } };   int main( int argc, char* argv[] ) { srand( GetTickCount() ); cocktailSort cs; int arr[EL_COUNT];   for( int x = 0; x < EL_COUNT; x++ ) arr[x] = rand() % EL_COUNT + 1;   std::cout << "Original: " << std::endl << "==========" << std::endl; for( int x = 0; x < EL_COUNT; x += LLEN ) { for( int s = x; s < x + LLEN; s++ ) std::cout << arr[s] << ", ";   std::cout << std::endl; }   //DWORD now = GetTickCount(); cs.sort( arr, EL_COUNT ); //now = GetTickCount() - now;   std::cout << std::endl << std::endl << "Sorted: " << std::endl << "========" << std::endl; for( int x = 0; x < EL_COUNT; x += LLEN ) { for( int s = x; s < x + LLEN; s++ ) std::cout << arr[s] << ", ";   std::cout << std::endl; }   std::cout << std::endl << std::endl << std::endl << std::endl; //std::cout << now << std::endl << std::endl; return 0; }  
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
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 This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Io
Io
List do( countingSort := method(min, max, count := list() setSize(max - min + 1) mapInPlace(0) foreach(x, count atPut(x - min, count at(x - min) + 1) )   j := 0 for(i, min, max, while(count at(i - min) > 0, atPut(j, i) count atPut(i - min, at(i - min) - 1) j = j + 1 ) ) self)   countingSortInPlace := method( countingSort(min, max) ) )   l := list(2, 3, -4, 5, 1) l countingSortInPlace println # ==> list(-4, 1, 2, 3, 5)
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#8086_Assembly
8086 Assembly
mov ax,6FFFh mov bx,3456h mov cx,0   ;We'll consider these sorted when ax <= bx <= cx.   SortRegisters proc cmp ax,bx jbe continue ;if we got here, ax > bx. We don't know the relationship between bx and cx at this time. cmp ax,cx jbe swap_ax_and_bx ;if we got here, ax > bx, and bx > cx. Therefore all we need to do is swap ax and cx, and we're done. xchg ax,cx jmp endOfProc   swap ax_and_bx: ;if we got here, ax > bx, and ax <= cx. So all we have to do is swap ax and bx, and we're done xchg ax,bx jmp end ;back to top     continue: ;if we got here, ax <= bx. cmp bx,cx jbe end ;if we got here, ax <= bx, and bx > cx. Therefore all we need to do is swap bx and cx, and we're done. xchg bx,cx     endOfProc: ;if we got here, ax <= bx, and bx <= cx. Therefore, ax <= bx <=cx and we are done. ;   SortRegisters endp
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#Ada
Ada
with Ada.Text_IO; with Ada.Strings.Unbounded;   procedure Sort_Three is   generic type Element_Type is private; with function "<" (Left, Right : in Element_Type) return Boolean; procedure Generic_Sort (X, Y, Z : in out Element_Type);   procedure Generic_Sort (X, Y, Z : in out Element_Type) is procedure Swap (Left, Right : in out Element_Type) is T : constant Element_Type := Left; begin Left := Right; Right := T; end Swap; begin if Y < X then Swap (X, Y); end if; if Z < Y then Swap (Y, Z); end if; if Y < X then Swap (X, Y); end if; end Generic_Sort;   procedure Test_Unbounded_Sort is use Ada.Text_IO; use Ada.Strings.Unbounded;   X : Unbounded_String := To_Unbounded_String ("lions, tigers, and"); Y : Unbounded_String := To_Unbounded_String ("bears, oh my!"); Z : Unbounded_String := To_Unbounded_String ("(from the ""Wizard of OZ"")");   procedure Sort is new Generic_Sort (Unbounded_String, "<"); begin Sort (X, Y, Z); Put_Line (To_String (X)); Put_Line (To_String (Y)); Put_Line (To_String (Z)); New_Line; End Test_Unbounded_Sort;   procedure Test_Integer_Sort is   use Ada.Text_IO;   procedure Sort is new Generic_Sort (Integer, "<");   X : Integer := 77444; Y : Integer := -12; Z : Integer := 0; begin Sort (X, Y, Z); Put_Line (X'Image); Put_Line (Y'Image); Put_Line (Z'Image); New_Line; end Test_Integer_Sort;   begin Test_Unbounded_Sort; Test_Integer_Sort; end Sort_Three;
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#AppleScript
AppleScript
use framework "Foundation"   -- SORTING LISTS OF ATOMIC (NON-RECORD) DATA WITH A CUSTOM SORT FUNCTION   -- In sortBy, f is a function from () to a tuple of two parts: -- 1. a function from any value to a record derived from (and containing) that value -- The base value should be present in the record under the key 'value' -- additional derivative keys (and optionally the 'value' key) should be included in 2: -- 2. a list of (record key, boolean) tuples, in the order of sort comparison, -- where the value *true* selects ascending order for the paired key -- and the value *false* selects descending order for that key   -- sortBy :: (() -> ((a -> Record), [(String, Bool)])) -> [a] -> [a] on sortBy(f, xs) set {fn, keyBools} to mReturn(f)'s |λ|() script unWrap on |λ|(x) value of x end |λ| end script map(unWrap, sortByComparing(keyBools, map(fn, xs))) end sortBy   -- SORTING APPLESCRIPT RECORDS BY PRIMARY AND N-ARY SORT KEYS   -- sortByComparing :: [(String, Bool)] -> [Records] -> [Records] on sortByComparing(keyDirections, xs) set ca to current application   script recDict on |λ|(x) ca's NSDictionary's dictionaryWithDictionary:x end |λ| end script set dcts to map(recDict, xs)   script asDescriptor on |λ|(kd) set {k, d} to kd ca's NSSortDescriptor's sortDescriptorWithKey:k ascending:d selector:dcts end |λ| end script   ((ca's NSArray's arrayWithArray:dcts)'s ¬ sortedArrayUsingDescriptors:map(asDescriptor, keyDirections)) as list end sortByComparing     -- GENERIC FUNCTIONS --------------------------------------------------------- -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- TEST ---------------------------------------------------------------------- on run set xs to ["Shanghai", "Karachi", "Beijing", "Sao Paulo", "Dhaka", "Delhi", "Lagos"]   -- Custom comparator:   -- Returns a lifting function and a sequence of {key, bool} pairs   -- Strings in order of descending length, -- and ascending lexicographic order script lengthDownAZup on |λ|() script on |λ|(x) {value:x, n:length of x} end |λ| end script {result, {{"n", false}, {"value", true}}} end |λ| end script   sortBy(lengthDownAZup, xs) end run
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detect and warn of at least two types of inconsistent indentation: inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces) inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces. Your code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units. You should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts. Your sort should not alter the type or size of the indentation units used in the input outline. (For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text [1] is available for inspection on Github). Tests Sort every level of the (4 space indented) outline below lexically, once ascending and once descending. zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Do the same with a tab-indented equivalent of the same outline. zeta gamma mu lambda kappa delta beta alpha theta iota epsilon The output sequence of an ascending lexical sort of each level should be: alpha epsilon iota theta zeta beta delta gamma kappa lambda mu The output sequence of a descending lexical sort of each level should be: zeta gamma mu lambda kappa delta beta alpha theta iota epsilon Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code. alpha epsilon iota theta zeta beta delta gamma kappa lambda mu zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Related tasks   Functional_coverage_tree   Display_an_outline_as_a_nested_table
#AutoHotkey
AutoHotkey
Sort_an_outline(data, reverse:=""){ ;----------------------- ; get Delim, Error Check for i, line in StrSplit(data, "`n", "`r") if !Delim RegExMatch(line, "^\h+", Delim) else if RegExMatch(RegExReplace(line, "^(" Delim ")*"), "^\h+") return "Error @ " line ;----------------------- ; ascending lexical sort ancestor:=[], tree:= [], result:="" for i, line in StrSplit(data, "`n", "`r"){ name := StrSplit(line, delim?delim:"`t") n := name.count() son := name[n] if (n>rank) && father ancestor.push(father) loop % rank-n ancestor.pop() for i, father in ancestor Lineage .= father . delim output .= Lineage son "`n" rank:=n, father:=son, Lineage:="" } Sort, output for i, line in StrSplit(output, "`n", "`r") name := StrSplit(line, delim) , result .= indent(name.count()-1, delim) . name[name.count()] "`n" if !reverse return Trim(result, "`n") ;----------------------- ; descending lexical sort ancestor:=[], Lineage:="", result:="" Sort, output, R for i, line in StrSplit(output, "`n", "`r"){ name := StrSplit(line, delim) if !ancestor[Lineage] loop % name.count() result .= indent(A_Index-1, delim) . name[A_Index] "`n" else if (StrSplit(Lineage, ",")[name.count()] <> name[name.count()]) result .= indent(name.count()-1, delim) . name[name.count()] "`n" Lineage := "" loop % name.count()-1 Lineage .= (Lineage ? "," : "") . name[A_Index] , ancestor[Lineage] := true } return result } indent(n, delim){ Loop, % n result.=delim return result }
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#Maple
Maple
swap := proc(arr, a, b) local temp; temp := arr[a]: arr[a] := arr[b]: arr[b] := temp: end proc: newGap := proc(gap) local new; new := trunc(gap*10/13); if (new < 1) then return 1; end if; return new; end proc; combsort := proc(arr, len) local gap, swapped,i, temp; swapped := true: gap := len: while ((not gap = 1) or swapped) do gap := newGap(gap): swapped := false: for i from 1 to len-gap by 1 do if (arr[i] > arr[i+gap]) then temp := arr[i]: arr[i] := arr[i+gap]: arr[i+gap] := temp: swapped:= true: end if: end do: end do: end proc: arr := Array([17,3,72,0,36,2,3,8,40,0]); combsort(arr, numelems(arr)); arr;
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Io
Io
List do( isSorted := method( slice(1) foreach(i, x, if (x < at(i), return false) ) return true; )   bogoSortInPlace := method( while(isSorted not, shuffleInPlace() ) ) )   lst := list(2, 1, 4, 3) lst bogoSortInPlace println # ==> list(1, 2, 3, 4), hopefully :)
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
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 A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#ALGOL_60
ALGOL 60
begin comment Sorting algorithms/Bubble sort - Algol 60; integer nA; nA:=20;   begin integer array A[1:20];   procedure bubblesort(lb,ub); value lb,ub; integer lb,ub; begin integer i; boolean swapped; swapped :=true; for i:=1 while swapped do begin swapped:=false; for i:=lb step 1 until ub-1 do if A[i]>A[i+1] then begin integer temp; temp  :=A[i]; A[i]  :=A[i+1]; A[i+1]:=temp; swapped:=true end end end bubblesort;   procedure inittable(lb,ub); value lb,ub; integer lb,ub; begin integer i; for i:=lb step 1 until ub do A[i]:=entier(rand*100) end inittable;   procedure writetable(lb,ub); value lb,ub; integer lb,ub; begin integer i; for i:=lb step 1 until ub do outinteger(1,A[i]); outstring(1,"\n") end writetable;     inittable(1,nA); writetable(1,nA); bubblesort(1,nA); writetable(1,nA) end end
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
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 This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Elixir
Elixir
defmodule Sort do def gnome_sort([]), do: [] def gnome_sort([h|t]), do: gnome_sort([h], t)   defp gnome_sort(list, []), do: list defp gnome_sort([prev|p], [next|n]) when next > prev, do: gnome_sort(p, [next,prev|n]) defp gnome_sort(p, [next|n]), do: gnome_sort([next|p], n) end   IO.inspect Sort.gnome_sort([8,3,9,1,3,2,6])
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
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 of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Eiffel
Eiffel
  class BEAD_SORT   feature   bead_sort (ar: ARRAY [INTEGER]): ARRAY [INTEGER] -- Sorted array in descending order. require only_positive_integers: across ar as a all a.item > 0 end local max, count, i, j, k: INTEGER do max := max_item (ar) create Result.make_filled (0, 1, ar.count) from i := 1 until i > max loop count := 0 from k := 1 until k > ar.count loop if ar.item (k) >= i then count := count + 1 end k := k + 1 end from j := 1 until j > count loop Result [j] := i j := j + 1 end i := i + 1 end ensure array_is_sorted: is_sorted (Result) end   feature {NONE}   max_item (ar: ARRAY [INTEGER]): INTEGER -- Max item of 'ar'. require ar_not_void: ar /= Void do across ar as a loop if a.item > Result then Result := a.item end end ensure Result_is_max: across ar as a all a.item <= Result end end   is_sorted (ar: ARRAY [INTEGER]): BOOLEAN --- Is 'ar' sorted in descending order? require ar_not_empty: ar.is_empty = False local i: INTEGER do Result := True from i := ar.lower until i = ar.upper loop if ar [i] < ar [i + 1] then Result := False end i := i + 1 end end   end  
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
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 This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#COBOL
COBOL
C-SORT SECTION. C-000. DISPLAY "SORT STARTING".   MOVE 2 TO WC-START MOVE WC-SIZE TO WC-END. MOVE 1 TO WC-DIRECTION WC-LAST-CHANGE. PERFORM E-SHAKER UNTIL WC-END * WC-DIRECTION < WC-START * WC-DIRECTION.   DISPLAY "SORT FINISHED".   C-999. EXIT.   E-SHAKER SECTION. E-000. PERFORM F-PASS VARYING WB-IX-1 FROM WC-START BY WC-DIRECTION UNTIL WB-IX-1 = WC-END + WC-DIRECTION.   MOVE WC-START TO WC-END. SUBTRACT WC-DIRECTION FROM WC-LAST-CHANGE GIVING WC-START. MULTIPLY WC-DIRECTION BY -1 GIVING WC-DIRECTION.   E-999. EXIT.   F-PASS SECTION. F-000. IF WB-ENTRY(WB-IX-1 - 1) > WB-ENTRY(WB-IX-1) SET WC-LAST-CHANGE TO WB-IX-1 MOVE WB-ENTRY(WB-IX-1 - 1) TO WC-TEMP MOVE WB-ENTRY(WB-IX-1) TO WB-ENTRY(WB-IX-1 - 1) MOVE WC-TEMP TO WB-ENTRY(WB-IX-1).   F-999. EXIT.
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
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 This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#IS-BASIC
IS-BASIC
  100 PROGRAM "CountSrt.bas" 110 RANDOMIZE 120 NUMERIC ARRAY(5 TO 24) 130 CALL INIT(ARRAY) 140 CALL WRITE(ARRAY) 150 CALL COUNTINGSORT(ARRAY) 160 CALL WRITE(ARRAY) 170 DEF INIT(REF A) 180 FOR I=LBOUND(A) TO UBOUND(A) 190 LET A(I)=RND(98)+1 200 NEXT 210 END DEF 220 DEF WRITE(REF A) 230 FOR I=LBOUND(A) TO UBOUND(A) 240 PRINT A(I); 250 NEXT 260 PRINT 270 END DEF 280 DEF FMIN(REF A) 290 LET T=INF 300 FOR I=LBOUND(A) TO UBOUND(A) 310 LET T=MIN(A(I),T) 320 NEXT 330 LET FMIN=T 340 END DEF 350 DEF FMAX(REF A) 360 LET T=-INF 370 FOR I=LBOUND(A) TO UBOUND(A) 380 LET T=MAX(A(I),T) 390 NEXT 400 LET FMAX=T 410 END DEF 420 DEF COUNTINGSORT(REF A) 430 LET MX=FMAX(A):LET MN=FMIN(A):LET Z=LBOUND(A) 440 NUMERIC COUNT(0 TO MX-MN) 450 FOR I=0 TO UBOUND(COUNT) 460 LET COUNT(I)=0 470 NEXT 480 FOR I=Z TO UBOUND(A) 490 LET COUNT(A(I)-MN)=COUNT(A(I)-MN)+1 500 NEXT 510 FOR I=MN TO MX 520 DO WHILE COUNT(I-MN)>0 530 LET A(Z)=I:LET Z=Z+1:LET COUNT(I-MN)=COUNT(I-MN)-1 540 LOOP 550 NEXT 560 END DEF
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
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 This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#J
J
csort =: monad define min =. <./y cnt =. 0 $~ 1+(>./y)-min for_a. y do. cnt =. cnt >:@{`[`]}~ a-min end. cnt # min+i.#cnt )
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
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 Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#11l
11l
V n = 13 print(sorted(Array(1..n), key' i -> String(i)))
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#Aime
Aime
integer a, b, c; index i; text x, y, z; record r;   x = "lions, tigers, and"; y = "bears, oh my!"; z = "(from the \"Wizard of OZ\")";   r.fit(x, x, y, y, z, z);   x = r.rf_pick; y = r.rf_pick; z = r.rf_pick;   o_form("~\n~\n~\n", x, y, z);   a = 77444; b = -12; c = 0;   i.fit(a, a, b, b, c, c);   a = i.if_pick; b = i.if_pick; c = i.if_pick;   o_form("~\n~\n~\n", a, b, c);
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#ALGOL_68
ALGOL 68
BEGIN # MODE that can hold integers and strings - would need to be extended to # # allow for other types # MODE INTORSTRING = UNION( INT, STRING ); # returns TRUE if a is an INT, FALSE otherwise # OP ISINT = ( INTORSTRING a )BOOL: CASE a IN (INT): TRUE OUT FALSE ESAC; # returns TRUE if a is an INT, FALSE otherwise # OP ISSTRING = ( INTORSTRING a )BOOL: CASE a IN (STRING): TRUE OUT FALSE ESAC; # returns the integer in a or 0 if a isn't an integer # OP TOINT = ( INTORSTRING a )INT: CASE a IN (INT i): i OUT 0 ESAC; # returns the string in a or "" if a isn't a string # OP TOSTRING = ( INTORSTRING a )STRING: CASE a IN (STRING s): s OUT "" ESAC; # returns TRUE if a < b, FALSE otherwise # # a and b must have the same type # PRIO LESSTHAN = 4; OP LESSTHAN = ( INTORSTRING a, b )BOOL: IF ISSTRING a AND ISSTRING b THEN # both strings # TOSTRING a < TOSTRING b ELIF ISINT a AND ISINT b THEN # both integers # TOINT a < TOINT b ELSE # different MODEs # FALSE FI # LESSTHAN # ; # exchanges the values of a and b # PRIO SWAP = 9; OP SWAP = ( REF INTORSTRING a, b )VOID: BEGIN INTORSTRING t := a; a := b; b := t END; # sorts a, b and c # PROC sort 3 = ( REF INTORSTRING a, b, c )VOID: BEGIN IF b LESSTHAN a THEN a SWAP b FI; IF c LESSTHAN a THEN a SWAP c FI; IF c LESSTHAN b THEN b SWAP c FI END # sort 3 # ;   # task test cases # INTORSTRING x, y, z; x := "lions, tigers, and"; y := "bears, oh my!"; z := "(from the ""Wizard of OZ"")"; sort 3( x, y, z ); print( ( x, newline, y, newline, z, newline ) ); x := 77444; y := -12; z := 0; sort 3( x, y, z ); print( ( x, newline, y, newline, z, newline ) ) END
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#AutoHotkey
AutoHotkey
numbers = 5,3,7,9,1,13,999,-4 strings = Here,are,some,sample,strings,to,be,sorted Sort, numbers, F IntegerSort D, Sort, strings, F StringLengthSort D, msgbox % numbers msgbox % strings   IntegerSort(a1, a2) { return a2 - a1 }   StringLengthSort(a1, a2){ return strlen(a1) - strlen(a2) }
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detect and warn of at least two types of inconsistent indentation: inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces) inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces. Your code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units. You should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts. Your sort should not alter the type or size of the indentation units used in the input outline. (For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text [1] is available for inspection on Github). Tests Sort every level of the (4 space indented) outline below lexically, once ascending and once descending. zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Do the same with a tab-indented equivalent of the same outline. zeta gamma mu lambda kappa delta beta alpha theta iota epsilon The output sequence of an ascending lexical sort of each level should be: alpha epsilon iota theta zeta beta delta gamma kappa lambda mu The output sequence of a descending lexical sort of each level should be: zeta gamma mu lambda kappa delta beta alpha theta iota epsilon Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code. alpha epsilon iota theta zeta beta delta gamma kappa lambda mu zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Related tasks   Functional_coverage_tree   Display_an_outline_as_a_nested_table
#Go
Go
package main   import ( "fmt" "math" "sort" "strings" )   func sortedOutline(originalOutline []string, ascending bool) { outline := make([]string, len(originalOutline)) copy(outline, originalOutline) // make copy in case we mutate it indent := "" del := "\x7f" sep := "\x00" var messages []string if strings.TrimLeft(outline[0], " \t") != outline[0] { fmt.Println(" outline structure is unclear") return } for i := 1; i < len(outline); i++ { line := outline[i] lc := len(line) if strings.HasPrefix(line, " ") || strings.HasPrefix(line, " \t") || line[0] == '\t' { lc2 := len(strings.TrimLeft(line, " \t")) currIndent := line[0 : lc-lc2] if indent == "" { indent = currIndent } else { correctionNeeded := false if (strings.ContainsRune(currIndent, '\t') && !strings.ContainsRune(indent, '\t')) || (!strings.ContainsRune(currIndent, '\t') && strings.ContainsRune(indent, '\t')) { m := fmt.Sprintf("corrected inconsistent whitespace use at line %q", line) messages = append(messages, indent+m) correctionNeeded = true } else if len(currIndent)%len(indent) != 0 { m := fmt.Sprintf("corrected inconsistent indent width at line %q", line) messages = append(messages, indent+m) correctionNeeded = true } if correctionNeeded { mult := int(math.Round(float64(len(currIndent)) / float64(len(indent)))) outline[i] = strings.Repeat(indent, mult) + line[lc-lc2:] } } } } levels := make([]int, len(outline)) levels[0] = 1 margin := "" for level := 1; ; level++ { allPos := true for i := 1; i < len(levels); i++ { if levels[i] == 0 { allPos = false break } } if allPos { break } mc := len(margin) for i := 1; i < len(outline); i++ { if levels[i] == 0 { line := outline[i] if strings.HasPrefix(line, margin) && line[mc] != ' ' && line[mc] != '\t' { levels[i] = level } } } margin += indent } lines := make([]string, len(outline)) lines[0] = outline[0] var nodes []string for i := 1; i < len(outline); i++ { if levels[i] > levels[i-1] { if len(nodes) == 0 { nodes = append(nodes, outline[i-1]) } else { nodes = append(nodes, sep+outline[i-1]) } } else if levels[i] < levels[i-1] { j := levels[i-1] - levels[i] nodes = nodes[0 : len(nodes)-j] } if len(nodes) > 0 { lines[i] = strings.Join(nodes, "") + sep + outline[i] } else { lines[i] = outline[i] } } if ascending { sort.Strings(lines) } else { maxLen := len(lines[0]) for i := 1; i < len(lines); i++ { if len(lines[i]) > maxLen { maxLen = len(lines[i]) } } for i := 0; i < len(lines); i++ { lines[i] = lines[i] + strings.Repeat(del, maxLen-len(lines[i])) } sort.Sort(sort.Reverse(sort.StringSlice(lines))) } for i := 0; i < len(lines); i++ { s := strings.Split(lines[i], sep) lines[i] = s[len(s)-1] if !ascending { lines[i] = strings.TrimRight(lines[i], del) } } if len(messages) > 0 { fmt.Println(strings.Join(messages, "\n")) fmt.Println() } fmt.Println(strings.Join(lines, "\n")) }   func main() { outline := []string{ "zeta", " beta", " gamma", " lambda", " kappa", " mu", " delta", "alpha", " theta", " iota", " epsilon", }   outline2 := make([]string, len(outline)) for i := 0; i < len(outline); i++ { outline2[i] = strings.ReplaceAll(outline[i], " ", "\t") }   outline3 := []string{ "alpha", " epsilon", " iota", " theta", "zeta", " beta", " delta", " gamma", " \t kappa", // same length but \t instead of space " lambda", " mu", }   outline4 := []string{ "zeta", " beta", " gamma", " lambda", " kappa", " mu", " delta", "alpha", " theta", " iota", " epsilon", }   fmt.Println("Four space indented outline, ascending sort:") sortedOutline(outline, true)   fmt.Println("\nFour space indented outline, descending sort:") sortedOutline(outline, false)   fmt.Println("\nTab indented outline, ascending sort:") sortedOutline(outline2, true)   fmt.Println("\nTab indented outline, descending sort:") sortedOutline(outline2, false)   fmt.Println("\nFirst unspecified outline, ascending sort:") sortedOutline(outline3, true)   fmt.Println("\nFirst unspecified outline, descending sort:") sortedOutline(outline3, false)   fmt.Println("\nSecond unspecified outline, ascending sort:") sortedOutline(outline4, true)   fmt.Println("\nSecond unspecified outline, descending sort:") sortedOutline(outline4, false) }
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
combSort[list_] := Module[{ gap = 0, listSize = 0, swaps = True}, gap = listSize = Length[list]; While[ !((gap <= 1) && (swaps == False)),   gap = Floor@Divide[gap, 1.25]; If[ gap < 1, gap = 1]; i = 1; swaps = False;   While[ ! ((i + gap - 1) >= listSize), If[ list[[i]] > list[[i + gap]], swaps = True; list[[i ;; i + gap]] = list[[i + gap ;; i ;; -1]]; ]; i++; ] ] ]
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#J
J
bogo=: monad define whilst. +./ 2 >/\ Ry do. Ry=. (A.~ ?@!@#) y end. Ry )
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
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 A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#ALGOL_68
ALGOL 68
MODE DATA = INT; PROC swap = (REF[]DATA slice)VOID: ( DATA tmp = slice[1]; slice[1] := slice[2]; slice[2] := tmp );   PROC sort = (REF[]DATA array)VOID: ( BOOL sorted; INT shrinkage := 0; FOR size FROM UPB array - 1 BY -1 WHILE sorted := TRUE; shrinkage +:= 1; FOR i FROM LWB array TO size DO IF array[i+1] < array[i] THEN swap(array[i:i+1]); sorted := FALSE FI OD; NOT sorted DO SKIP OD );   main:( [10]INT random := (1,6,3,5,2,9,8,4,7,0);   printf(($"Before: "10(g(3))l$,random)); sort(random); printf(($"After: "10(g(3))l$,random)) )
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
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 This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Erlang
Erlang
-module(gnome_sort). -export([gnome/1]).   gnome(L, []) -> L; gnome([Prev|P], [Next|N]) when Next > Prev -> gnome(P, [Next|[Prev|N]]); gnome(P, [Next|N]) -> gnome([Next|P], N). gnome([H|T]) -> gnome([H], T).
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
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 of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Elixir
Elixir
defmodule Sort do def bead_sort(list) when is_list(list), do: dist(dist(list))   defp dist(list), do: List.foldl(list, [], fn(n, acc) when n>0 -> dist(acc, n, []) end)   defp dist([], 0, acc), do: Enum.reverse(acc) defp dist([h|t], 0, acc), do: dist(t, 0, [h |acc]) defp dist([], n, acc), do: dist([], n-1, [1 |acc]) defp dist([h|t], n, acc), do: dist(t, n-1, [h+1|acc]) end
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
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 of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Erlang
Erlang
-module(beadsort).   -export([sort/1]).   sort(L) -> dist(dist(L)).   dist(L) when is_list(L) -> lists:foldl(fun (N, Acc) -> dist(Acc, N, []) end, [], L).   dist([H | T], N, Acc) when N > 0 -> dist(T, N - 1, [H + 1 | Acc]); dist([], N, Acc) when N > 0 -> dist([], N - 1, [1 | Acc]); dist([H | T], 0, Acc) -> dist(T, 0, [H | Acc]); dist([], 0, Acc) -> lists:reverse(Acc).
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
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 This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Common_Lisp
Common Lisp
(defun cocktail-sort-vector (vector predicate &aux (len (length vector))) (labels ((scan (start step &aux swapped) (loop for i = start then (+ i step) while (< 0 i len) do (when (funcall predicate (aref vector i) (aref vector (1- i))) (rotatef (aref vector i) (aref vector (1- i))) (setf swapped t))) swapped)) (loop while (and (scan 1 1) (scan (1- len) -1)))) vector)   (defun cocktail-sort (sequence predicate) (etypecase sequence (vector (cocktail-sort-vector sequence predicate)) (list (map-into sequence 'identity (cocktail-sort-vector (coerce sequence 'vector) predicate)))))
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
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 This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Java
Java
public static void countingSort(int[] array, int min, int max){ int[] count= new int[max - min + 1]; for(int number : array){ count[number - min]++; } int z= 0; for(int i= min;i <= max;i++){ while(count[i - min] > 0){ array[z]= i; z++; count[i - min]--; } } }
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
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 Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Action.21
Action!
PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   INT FUNC Compare(INT a1,a2) CHAR ARRAY s1(10),s2(10) INT res   StrI(a1,s1) StrI(a2,s2) res=SCompare(s1,s2) RETURN (res)   PROC InsertionSort(INT ARRAY a INT size) INT i,j,value   FOR i=1 TO size-1 DO value=a(i) j=i-1 WHILE j>=0 AND Compare(a(j),value)>0 DO a(j+1)=a(j) j==-1 OD a(j+1)=value OD RETURN   PROC Test(INT ARRAY a INT size) PrintE("Array before sort:") PrintArray(a,size) InsertionSort(a,size) PrintE("Array after sort:") PrintArray(a,size) PutE() RETURN   PROC Main() DEFINE COUNT_A="13" DEFINE COUNT_B="50" INT ARRAY a(COUNT_A),b(COUNT_B) BYTE i   FOR i=1 TO COUNT_A DO a(i-1)=i OD   FOR i=1 TO COUNT_B DO b(i-1)=i OD   Test(a,COUNT_A) Test(b,COUNT_B) RETURN
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
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 Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Ada
Ada
WITH Ada.Containers.Generic_Array_Sort, Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Natural_Array IS ARRAY (Positive RANGE <>) OF Natural; FUNCTION Less (L, R : Natural) RETURN Boolean IS (L'Img < R'Img); PROCEDURE Sort_Naturals IS NEW Ada.Containers.Generic_Array_Sort (Positive, Natural, Natural_Array, Less); PROCEDURE Show (Last : Natural) IS A : Natural_Array (1 .. Last); BEGIN FOR I IN A'Range LOOP A (I) := I; END LOOP; Sort_Naturals (A); FOR I IN A'Range LOOP Put (A (I)'Img); END LOOP; New_Line; END Show; BEGIN Show (13); Show (21); END Main;  
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
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 Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#APL
APL
{⍎¨{⍵[⍋⍵]}⍕¨1+⍳⍵} 13 1 10 11 12 13 2 3 4 5 6 7 8 9 {⍎¨{⍵[⍋⍵]}⍕¨1+⍳⍵} 21 1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#APL
APL
x y z←{⍵[⍋⍵]}x y z
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#AppleScript
AppleScript
set x to "lions, tigers, and" set y to "bears, oh my!" set z to "(from the \"Wizard of OZ\")"   if (x > y) then set {x, y} to {y, x} if (y > z) then set {y, z} to {z, y} if (x > y) then set {x, y} to {y, x} end if   return {x, y, z}
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#AWK
AWK
# syntax: GAWK -f SORT_USING_A_CUSTOM_COMPARATOR.AWK # # sorting: # PROCINFO["sorted_in"] is used by GAWK # SORTTYPE is used by Thompson Automation's TAWK # BEGIN { words = "This Is A Set Of Strings To Sort duplicated" n = split(words " " tolower(words),tmp_arr," ") print("unsorted:") for (i=1; i<=n; i++) { word = tmp_arr[i] arr[length(word)][word]++ print(word) } print("\nsorted:") PROCINFO["sorted_in"] = "@ind_num_desc" ; SORTTYPE = 9 for (i in arr) { PROCINFO["sorted_in"] = "caselessCompare" ; SORTTYPE = 2 # possibly 14? for (j in arr[i]) { for (k=1; k<=arr[i][j]; k++) { print(j) } } } exit(0) } function caselessCompare( i1, v1, i2, v2, l1, l2, result ) { l1 = tolower( i1 ); l2 = tolower( i2 ); return ( ( l1 < l2 ) ? -1 : ( ( l1 == l2 ) ? 0 : 1 ) ); } # caselessCompare
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detect and warn of at least two types of inconsistent indentation: inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces) inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces. Your code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units. You should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts. Your sort should not alter the type or size of the indentation units used in the input outline. (For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text [1] is available for inspection on Github). Tests Sort every level of the (4 space indented) outline below lexically, once ascending and once descending. zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Do the same with a tab-indented equivalent of the same outline. zeta gamma mu lambda kappa delta beta alpha theta iota epsilon The output sequence of an ascending lexical sort of each level should be: alpha epsilon iota theta zeta beta delta gamma kappa lambda mu The output sequence of a descending lexical sort of each level should be: zeta gamma mu lambda kappa delta beta alpha theta iota epsilon Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code. alpha epsilon iota theta zeta beta delta gamma kappa lambda mu zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Related tasks   Functional_coverage_tree   Display_an_outline_as_a_nested_table
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   import Data.Tree (Tree(..), foldTree) import qualified Data.Text.IO as T import qualified Data.Text as T import qualified Data.List as L import Data.Bifunctor (first) import Data.Ord (comparing) import Data.Char (isSpace)     --------------- OUTLINE SORTED AT EVERY LEVEL --------------   sortedOutline :: (Tree T.Text -> Tree T.Text -> Ordering) -> T.Text -> Either T.Text T.Text sortedOutline cmp outlineText = let xs = T.lines outlineText in consistentIndentUnit (nonZeroIndents xs) >>= \indentUnit -> let forest = forestFromLineIndents $ indentLevelsFromLines xs sortedForest = subForest $ foldTree (\x xs -> Node x (L.sortBy cmp xs)) (Node "" forest) in Right $ outlineFromForest indentUnit sortedForest     --------------------------- TESTS --------------------------   main :: IO () main = mapM_ T.putStrLn $ concat $ [ \(comparatorLabel, cmp) -> (\kv -> let section = headedSection (fst kv) comparatorLabel in (either (section . (" -> " <>)) section . sortedOutline cmp . snd) kv) <$> [ ("Four-spaced", spacedOutline) , ("Tabbed", tabbedOutline) , ("First unknown type", confusedOutline) , ("Second unknown type", raggedOutline) ] ] <*> [("(A -> Z)", comparing rootLabel), ("(Z -> A)", flip (comparing rootLabel))]   headedSection :: T.Text -> T.Text -> T.Text -> T.Text headedSection outlineType comparatorName x = T.concat ["\n", outlineType, " ", comparatorName, ":\n\n", x]   spacedOutline, tabbedOutline, confusedOutline, raggedOutline :: T.Text spacedOutline = "zeta\n\ \ beta\n\ \ gamma\n\ \ lambda\n\ \ kappa\n\ \ mu\n\ \ delta\n\ \alpha\n\ \ theta\n\ \ iota\n\ \ epsilon"   tabbedOutline = "zeta\n\ \\tbeta\n\ \\tgamma\n\ \\t\tlambda\n\ \\t\tkappa\n\ \\t\tmu\n\ \\tdelta\n\ \alpha\n\ \\ttheta\n\ \\tiota\n\ \\tepsilon"   confusedOutline = "zeta\n\ \ beta\n\ \ gamma\n\ \ lambda\n\ \ \t kappa\n\ \ mu\n\ \ delta\n\ \alpha\n\ \ theta\n\ \ iota\n\ \ epsilon"   raggedOutline = "zeta\n\ \ beta\n\ \ gamma\n\ \ lambda\n\ \ kappa\n\ \ mu\n\ \ delta\n\ \alpha\n\ \ theta\n\ \ iota\n\ \ epsilon"     -------- OUTLINE TREES :: SERIALIZED AND DESERIALIZED ------   forestFromLineIndents :: [(Int, T.Text)] -> [Tree T.Text] forestFromLineIndents = go where go [] = [] go ((n, s):xs) = Node s (go subOutline) : go rest where (subOutline, rest) = span ((n <) . fst) xs   indentLevelsFromLines :: [T.Text] -> [(Int, T.Text)] indentLevelsFromLines xs = first (`div` indentUnit) <$> pairs where pairs = first T.length . T.span isSpace <$> xs indentUnit = maybe 1 fst (L.find ((0 <) . fst) pairs)   outlineFromForest :: T.Text -> [Tree T.Text] -> T.Text outlineFromForest tabString forest = T.unlines $ forest >>= go "" where go indent node = indent <> rootLabel node : (subForest node >>= go (T.append tabString indent))   ------ OUTLINE CHECKING - INDENT CHARACTERS AND WIDTHS ----- consistentIndentUnit :: [T.Text] -> Either T.Text T.Text consistentIndentUnit prefixes = minimumIndent prefixes >>= checked prefixes where checked xs indentUnit | all ((0 ==) . (`rem` unitLength) . T.length) xs = Right indentUnit | otherwise = Left ("Inconsistent indent depths: " <> T.pack (show (T.length <$> prefixes))) where unitLength = T.length indentUnit   minimumIndent :: [T.Text] -> Either T.Text T.Text minimumIndent prefixes = go $ T.foldr newChar "" $ T.concat prefixes where newChar c seen | c `L.elem` seen = seen | otherwise = c : seen go cs | 1 < length cs = Left $ "Mixed indent characters used: " <> T.pack (show cs) | otherwise = Right $ L.minimumBy (comparing T.length) prefixes   nonZeroIndents :: [T.Text] -> [T.Text] nonZeroIndents textLines = [ s | x <- textLines , s <- [T.takeWhile isSpace x] , 0 /= T.length s ]
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#MATLAB_.2F_Octave
MATLAB / Octave
function list = combSort(list)   listSize = numel(list); gap = int32(listSize); %Coerce gap to an int so we can use the idivide function swaps = true; %Swap flag   while not((gap <= 1) && (swaps == false))   gap = idivide(gap,1.25,'floor'); %Int divide, floor the resulting operation   if gap < 1 gap = 1; end   i = 1; %i equals 1 because all arrays are 1 based in MATLAB swaps = false;   %i + gap must be subtracted by 1 because the pseudo-code was writen %for 0 based arrays while not((i + gap - 1) >= listSize)   if (list(i) > list(i+gap)) list([i i+gap]) = list([i+gap i]); %swap swaps = true; end i = i + 1;   end %while end %while end %combSort
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Java
Java
    public class BogoSort { public static void main(String[] args) { //Enter array to be sorted here int[] arr={4,5,6,0,7,8,9,1,2,3};   BogoSort now=new BogoSort(); System.out.print("Unsorted: "); now.display1D(arr);   now.bogo(arr);   System.out.print("Sorted: "); now.display1D(arr); } void bogo(int[] arr) { //Keep a track of the number of shuffles int shuffle=1; for(;!isSorted(arr);shuffle++) shuffle(arr); //Boast System.out.println("This took "+shuffle+" shuffles."); } void shuffle(int[] arr) { //Standard Fisher-Yates shuffle algorithm int i=arr.length-1; while(i>0) swap(arr,i--,(int)(Math.random()*i)); } void swap(int[] arr,int i,int j) { int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } boolean isSorted(int[] arr) {   for(int i=1;i<arr.length;i++) if(arr[i]<arr[i-1]) return false; return true; } void display1D(int[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); }   }  
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
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 A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#ALGOL_W
ALGOL W
begin  % As algol W does not allow overloading, we have to have type-specific  %  % sorting procedures - this bubble sorts an integer array  %  % as there is no way for the procedure to determine the array bounds, we %  % pass the lower and upper bounds in lb and ub  % procedure bubbleSortIntegers( integer array item( * )  ; integer value lb  ; integer value ub ) ; begin integer lower, upper;   lower := lb; upper := ub;   while begin logical swapped; upper  := upper - 1; swapped := false; for i := lower until upper do begin if item( i ) > item( i + 1 ) then begin integer val; val  := item( i ); item( i )  := item( i + 1 ); item( i + 1 ) := val; swapped  := true; end if_must_swap ; end for_i ; swapped end do begin end; end bubbleSortIntegers ;   begin % test the bubble sort  % integer array data( 1 :: 10 );   procedure writeData ; begin write( data( 1 ) ); for i := 2 until 10 do writeon( data( i ) ); end writeData ;    % initialise data to unsorted values  % integer dPos; dPos  := 1; for i := 16, 2, -6, 9, 90, 14, 0, 23, 8, 9 do begin data( dPos ) := i; dPos  := dPos + 1; end for_i ;   i_w := 3; s_w := 1; % set output format % writeData; bubbleSortIntegers( data, 1, 10 ); writeData; end test end.
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
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 This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Euphoria
Euphoria
function gnomeSort(sequence s) integer i,j object temp i = 1 j = 2 while i < length(s) do if compare(s[i], s[i+1]) <= 0 then i = j j += 1 else temp = s[i] s[i] = s[i+1] s[i+1] = temp i -= 1 if i = 0 then i = j j += 1 end if end if end while return s end function
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
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 of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#F.23
F#
open System   let removeEmptyLists lists = lists |> List.filter (not << List.isEmpty) let flip f x y = f y x   let rec transpose = function | [] -> [] | lists -> (List.map List.head lists) :: transpose(removeEmptyLists (List.map List.tail lists))   // Using the backward composition operator "<<" (equivalent to Haskells ".") ... let beadSort = List.map List.sum << transpose << transpose << List.map (flip List.replicate 1)   // Using the forward composition operator ">>" ... let beadSort2 = List.map (flip List.replicate 1) >> transpose >> transpose >> List.map List.sum
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
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 This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#D
D
// Written in the D programming language. module rosettaCode.sortingAlgorithms.cocktailSort;   import std.range;   Range cocktailSort(Range)(Range data) if (isRandomAccessRange!Range && hasLvalueElements!Range) { import std.algorithm : swap; bool swapped = void; void trySwap(E)(ref E lhs, ref E rhs) { if (lhs > rhs) { swap(lhs, rhs); swapped = true; } }   if (data.length > 0) do { swapped = false; foreach (i; 0 .. data.length - 1) trySwap(data[i], data[i + 1]); if (!swapped) break; swapped = false; foreach_reverse (i; 0 .. data.length - 1) trySwap(data[i], data[i + 1]); } while(swapped); return data; }   unittest { assert (cocktailSort([3, 1, 5, 2, 4]) == [1, 2, 3, 4, 5]); assert (cocktailSort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]); assert (cocktailSort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]); assert (cocktailSort((int[]).init) == []); assert (cocktailSort(["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]) == ["Alice", "Jane", "Joe", "John", "Kate", "Zerg"]); }  
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
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 This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#JavaScript
JavaScript
var countSort = function(arr, min, max) { var i, z = 0, count = [];   for (i = min; i <= max; i++) { count[i] = 0; }   for (i=0; i < arr.length; i++) { count[arr[i]]++; }   for (i = min; i <= max; i++) { while (count[i]-- > 0) { arr[z++] = i; } }   }
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
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 Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#AppleScript
AppleScript
on oneToNLexicographically(n) script o property output : {}   on otnl(i) set j to i + 9 - i mod 10 if (j > n) then set j to n repeat with i from i to j set end of my output to i tell i * 10 to if (it ≤ n) then my otnl(it) end repeat end otnl end script   o's otnl(1)   return o's output end oneToNLexicographically   -- Test code: oneToNLexicographically(13) --> {1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9}   oneToNLexicographically(123) --> {1, 10, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 11, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 12, 120, 121, 122, 123, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 4, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 6, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 7, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 8, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 9, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99}
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
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 Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Arturo
Arturo
arr: 1..13 print sort map arr => [to :string]
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#Arturo
Arturo
x: {lions, tigers, and} y: {bears, oh my!} z: {(from the "Wizard of OZ")}   print join.with:"\n" sort @[x y z]   x: 125 y: neg 2 z: pi   print sort @[x y z]
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#AutoHotkey
AutoHotkey
SortThreeVariables(ByRef x,ByRef y,ByRef z){ obj := [] for k, v in (var := StrSplit("x,y,z", ",")) obj[%v%] := true for k, v in obj temp := var[A_Index], %temp% := k }
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Babel
Babel
babel> ("Here" "are" "some" "sample" "strings" "to" "be" "sorted") strsort ! lsstr ! ( "Here" "are" "be" "sample" "some" "sorted" "strings" "to" ) babel> ("Here" "are" "some" "sample" "strings" "to" "be" "sorted") lexsort ! lsstr ! ( "be" "to" "are" "Here" "some" "sample" "sorted" "strings" )
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Burlesque
Burlesque
  blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}>< {"ADD" "Abc" "Acb" "acb" "acc"} blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}(zz)CMsb {"Abc" "acb" "Acb" "acc" "ADD"}  
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detect and warn of at least two types of inconsistent indentation: inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces) inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces. Your code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units. You should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts. Your sort should not alter the type or size of the indentation units used in the input outline. (For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text [1] is available for inspection on Github). Tests Sort every level of the (4 space indented) outline below lexically, once ascending and once descending. zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Do the same with a tab-indented equivalent of the same outline. zeta gamma mu lambda kappa delta beta alpha theta iota epsilon The output sequence of an ascending lexical sort of each level should be: alpha epsilon iota theta zeta beta delta gamma kappa lambda mu The output sequence of a descending lexical sort of each level should be: zeta gamma mu lambda kappa delta beta alpha theta iota epsilon Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code. alpha epsilon iota theta zeta beta delta gamma kappa lambda mu zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Related tasks   Functional_coverage_tree   Display_an_outline_as_a_nested_table
#Julia
Julia
import Base.print   abstract type Entry end   mutable struct OutlineEntry <: Entry level::Int text::String parent::Union{Entry, Nothing} children::Vector{Entry} end   mutable struct Outline root::OutlineEntry entries::Vector{OutlineEntry} baseindent::String end   rootentry() = OutlineEntry(0, "", nothing, []) indentchar(ch) = ch == ' ' || ch == '\t' firsttext(s) = something(findfirst(!indentchar, s), length(s) + 1) splitline(s) = begin i = firsttext(s); i == 1 ? ("", s) : (s[1:i-1], s[i:end]) end   const _indents = [" "]   function Base.print(io::IO, oe::OutlineEntry) println(io, _indents[end]^oe.level, oe.text) for child in oe.children print(io, child) end end   function Base.print(io::IO, o::Outline) push!(_indents, o.baseindent) print(io, o.root) pop!(_indents) end   function firstindent(lines, default = " ") for lin in lines s1, s2 = splitline(lin) s1 != "" && return s1 end return default end   function Outline(str::String) arr, lines = OutlineEntry[], filter(x -> x != "", split(str, r"\r\n|\n|\r")) root, indent, parentindex, lastindents = rootentry(), firstindent(lines), 0, 0 if ' ' in indent && '\t' in indent throw("Mixed tabs and spaces in indent are not allowed") end indentlen, indentregex = length(indent), Regex(indent) for (i, lin) in enumerate(lines) header, txt = splitline(lin) indentcount = length(collect(eachmatch(indentregex, header))) (indentcount * indentlen < length(header)) && throw("Error: bad indent " * string(UInt8.([c for c in header])) * ", expected " * string(UInt8.([c for c in indent]))) if indentcount > lastindents parentindex = i - 1 elseif indentcount < lastindents parentindex = something(findlast(x -> x.level == indentcount - 1, arr), 0) end lastindents = indentcount ent = OutlineEntry(indentcount, txt, parentindex == 0 ? root : arr[parentindex], []) push!(ent.parent.children, ent) push!(arr, ent) end return Outline(root, arr, indent) end   function sorttree!(ent::OutlineEntry, rev=false, level=0) for child in ent.children sorttree!(child, rev) end if level == 0 || level == ent.level sort!(ent.children, lt=(x, y) -> x.text < y.text, rev=rev) end return ent end   outlinesort!(ol::Outline, rev=false, lev=0) = begin sorttree!(ol.root, rev, lev); ol end   const outline4s = Outline(""" zeta beta gamma lambda kappa mu delta alpha theta iota epsilon""")   const outlinet1 = Outline(""" zeta gamma mu lambda kappa delta beta alpha theta iota epsilon""")   println("Given the text:\n", outline4s) println("Sorted outline is:\n", outlinesort!(outline4s)) println("Reverse sorted is:\n", outlinesort!(outline4s, true))   println("Using the text:\n", outlinet1) println("Sorted outline is:\n", outlinesort!(outlinet1)) println("Reverse sorted is:\n", outlinesort!(outlinet1, true)) println("Sorting only third level:\n", outlinesort!(outlinet1, false, 3))   try println("Trying to parse a bad outline:") outlinebad1 = Outline(""" alpha epsilon iota theta zeta beta delta gamma kappa lambda mu""") catch y println(y) end   try println("Trying to parse another bad outline:") outlinebad2 = Outline(""" zeta beta gamma lambda kappa mu delta alpha theta iota epsilon""") catch y println(y) end  
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detect and warn of at least two types of inconsistent indentation: inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces) inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces. Your code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units. You should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts. Your sort should not alter the type or size of the indentation units used in the input outline. (For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text [1] is available for inspection on Github). Tests Sort every level of the (4 space indented) outline below lexically, once ascending and once descending. zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Do the same with a tab-indented equivalent of the same outline. zeta gamma mu lambda kappa delta beta alpha theta iota epsilon The output sequence of an ascending lexical sort of each level should be: alpha epsilon iota theta zeta beta delta gamma kappa lambda mu The output sequence of a descending lexical sort of each level should be: zeta gamma mu lambda kappa delta beta alpha theta iota epsilon Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code. alpha epsilon iota theta zeta beta delta gamma kappa lambda mu zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Related tasks   Functional_coverage_tree   Display_an_outline_as_a_nested_table
#Nim
Nim
import algorithm, sequtils, strformat, strutils   type   OutlineEntry = ref object level: Natural text: string parent: OutlineEntry children: seq[OutlineEntry]   Outline = object root: OutlineEntry baseIndent: string     proc splitLine(line: string): (string, string) = for i, ch in line: if ch notin {' ', '\t'}: return (line[0..<i], line[i..^1]) result = (line, "")     proc firstIndent(lines: seq[string]; default = " "): string = for line in lines: result = line.splitLine()[0] if result.len != 0: return result = default     proc parent(arr: seq[OutlineEntry]; parentLevel: Natural): int = for i in countdown(arr.high, 0): if arr[i].level == parentLevel: return i     proc initOutline(str: string): Outline =   let root = OutlineEntry() var arr = @[root] # Outline entry at level 0 is root. let lines = str.splitLines().filterIt(it.len != 0) let indent = lines.firstIndent() var parentIndex = 0 var lastIndents = 0   if ' ' in indent and '\t' in indent: raise newException(ValueError, "Mixed tabs and spaces in indent are not allowed")   let indentLen = indent.len   for i, line in lines: let (header, txt) = line.splitLine() let indentCount = header.count(indent) if indentCount * indentLen != header.len: raise newException( ValueError, &"Error: bad indent 0x{header.toHex}, expected 0x{indent.toHex}") if indentCount > lastIndents: parentIndex = i elif indentCount < lastIndents: parentIndex = arr.parent(indentCount) lastIndents = indentCount let entry = OutlineEntry(level: indentCount + 1, text: txt, parent: arr[parentIndex]) entry.parent.children.add entry arr.add entry   result = Outline(root: root, baseIndent: indent)     proc sort(entry: OutlineEntry; order = Ascending; level = 0) = ## Sort an outline entry in place. for child in entry.children.mitems: child.sort(order) if level == 0 or level == entry.level: entry.children.sort(proc(x, y: OutlineEntry): int = cmp(x.text, y.text), order)     proc sort(outline: var Outline; order = Ascending; level = 0) = ## Sort an outline. outline.root.sort(order, level)     proc `$`(outline: Outline): string = ## Return the string representation of an outline.   proc `$`(entry: OutlineEntry): string = ## Return the string representation of an outline entry. result = repeat(outline.baseIndent, entry.level) & entry.text & '\n' for child in entry.children: result.add $child   result = $outline.root     var outline4s = initOutline(""" zeta beta gamma lambda kappa mu delta alpha theta iota epsilon""")   var outlinet1 = initOutline(""" zeta gamma mu lambda kappa delta beta alpha theta iota epsilon""")   echo "Given the text:\n", outline4s outline4s.sort() echo "Sorted outline is:\n", outline4s outline4s.sort(Descending) echo "Reverse sorted is:\n", outline4s   echo "Using the text:\n", outlinet1 outlinet1.sort() echo "Sorted outline is:\n", outlinet1 outlinet1.sort(Descending) echo "Reverse sorted is:\n", outlinet1 outlinet1.sort(level = 3) echo "Sorting only third level:\n", outlinet1   try: echo "Trying to parse a bad outline:" var outlinebad1 = initOutline(""" alpha epsilon iota theta zeta beta delta gamma kappa lambda mu""") except ValueError: echo getCurrentExceptionMsg()   try: echo "Trying to parse another bad outline:" var outlinebad2 = initOutline(""" zeta beta gamma lambda kappa mu delta alpha theta iota epsilon""") except ValueError: echo getCurrentExceptionMsg()
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detect and warn of at least two types of inconsistent indentation: inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces) inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces. Your code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units. You should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts. Your sort should not alter the type or size of the indentation units used in the input outline. (For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text [1] is available for inspection on Github). Tests Sort every level of the (4 space indented) outline below lexically, once ascending and once descending. zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Do the same with a tab-indented equivalent of the same outline. zeta gamma mu lambda kappa delta beta alpha theta iota epsilon The output sequence of an ascending lexical sort of each level should be: alpha epsilon iota theta zeta beta delta gamma kappa lambda mu The output sequence of a descending lexical sort of each level should be: zeta gamma mu lambda kappa delta beta alpha theta iota epsilon Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code. alpha epsilon iota theta zeta beta delta gamma kappa lambda mu zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Related tasks   Functional_coverage_tree   Display_an_outline_as_a_nested_table
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Sort_an_outline_at_every_level use warnings;   for my $test ( split /^(?=#)/m, join '', <DATA> ) { my ( $id, $outline ) = $test =~ /(\V*?\n)(.*)/s; my $sorted = validateandsort( $outline, $id =~ /descend/ ); print $test, '=' x 20, " answer:\n$sorted\n"; }   sub validateandsort { my ($outline, $descend) = @_; $outline =~ /^\h*(?: \t|\t )/m and return "ERROR: mixed tab and space indentaion\n"; my $adjust = 0; $adjust++ while $outline =~ s/^(\h*)\H.*\n\1\K\h(?=\H)//m or $outline =~ s/^(\h*)(\h)\H.*\n\1\K(?=\H)/$2/m; $adjust and print "WARNING: adjusting indentation on some lines\n"; return levelsort($outline, $descend); }   sub levelsort # outline_section, descend_flag { my ($section, $descend) = @_; my @parts; while( $section =~ / ((\h*) .*\n) ( (?:\2\h.*\n)* )/gx ) { my ($head, $rest) = ($1, $3); push @parts, $head . ( $rest and levelsort($rest, $descend) ); } join '', $descend ? reverse sort @parts : sort @parts; }   __DATA__ # 4 space ascending zeta beta gamma lambda kappa mu delta alpha theta iota epsilon # 4 space descending zeta beta gamma lambda kappa mu delta alpha theta iota epsilon   # mixed tab and space alpha epsilon iota theta zeta beta delta gamma kappa lambda mu # off alignment zeta beta gamma lambda kappa mu delta alpha theta iota epsilon
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#MAXScript
MAXScript
fn combSort arr = ( local gap = arr.count local swaps = 1 while not (gap == 1 and swaps == 0) do ( gap = (gap / 1.25) as integer if gap < 1 do ( gap = 1 ) local i = 1 swaps = 0 while not (i + gap > arr.count) do ( if arr[i] > arr[i+gap] do ( swap arr[i] arr[i+gap] swaps = 1 ) i += 1   )     ) return arr )
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#JavaScript
JavaScript
shuffle = function(v) { for(var j, x, i = v.length; i; j = Math.floor(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x); return v; };   isSorted = function(v){ for(var i=1; i<v.length; i++) { if (v[i-1] > v[i]) { return false; } } return true; }   bogosort = function(v){ var sorted = false; while(sorted == false){ v = shuffle(v); sorted = isSorted(v); } return v; }
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
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 A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#AppleScript
AppleScript
-- In-place bubble sort. on bubbleSort(theList, l, r) -- Sort items l thru r of theList. set listLen to (count theList) if (listLen < 2) then return -- Convert negative and/or transposed range indices. if (l < 0) then set l to listLen + l + 1 if (r < 0) then set r to listLen + r + 1 if (l > r) then set {l, r} to {r, l}   -- The list as a script property to allow faster references to its items. script o property lst : theList end script   set lPlus1 to l + 1 repeat with j from r to lPlus1 by -1 set lv to o's lst's item l -- Hereafter lv is only set when necessary and from rv rather than from the list. repeat with i from lPlus1 to j set rv to o's lst's item i if (lv > rv) then set o's lst's item (i - 1) to rv set o's lst's item i to lv else set lv to rv end if end repeat end repeat   return -- nothing. end bubbleSort property sort : bubbleSort   -- Demo: local aList set aList to {61, 23, 11, 55, 1, 94, 71, 98, 70, 33, 29, 77, 58, 95, 2, 52, 68, 29, 27, 37, 74, 38, 45, 73, 10} sort(aList, 1, -1) -- Sort items 1 thru -1 of aList. return aList
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
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 This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#F.23
F#
let inline gnomeSort (a: _ []) = let rec loop i j = if i < a.Length then if a.[i-1] <= a.[i] then loop j (j+1) else let t = a.[i-1] a.[i-1] <- a.[i] a.[i] <- t if i=1 then loop j (j+1) else loop (i-1) j loop 1 2
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
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 of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Factor
Factor
USING: kernel math math.order math.vectors sequences ; : fill ( seq len -- newseq ) [ dup length ] dip swap - 0 <repetition> append ;   : bead ( seq -- newseq ) dup 0 [ max ] reduce [ swap 1 <repetition> swap fill ] curry map [ ] [ v+ ] map-reduce ;   : beadsort ( seq -- newseq ) bead bead ;
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
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 of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Fortran
Fortran
program BeadSortTest use iso_fortran_env ! for ERROR_UNIT; to make this a F95 code, ! remove prev. line and declare ERROR_UNIT as an ! integer parameter matching the unit associated with ! standard error   integer, dimension(7) :: a = (/ 7, 3, 5, 1, 2, 1, 20 /)   call beadsort(a) print *, a   contains   subroutine beadsort(a) integer, dimension(:), intent(inout) :: a   integer, dimension(maxval(a), maxval(a)) :: t integer, dimension(maxval(a)) :: s integer :: i, m   m = maxval(a)   if ( any(a < 0) ) then write(ERROR_UNIT,*) "can't sort" return end if   t = 0 forall(i=1:size(a)) t(i, 1:a(i)) = 1 ! set up abacus forall(i=1:m) ! let beads "fall"; instead of s(i) = sum(t(:, i)) ! moving them one by one, we just t(:, i) = 0 ! count how many should be at bottom, t(1:s(i), i) = 1 ! and then "reset" and set only those end forall   forall(i=1:size(a)) a(i) = sum(t(i,:))   end subroutine beadsort   end program BeadSortTest
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
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 This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Delphi
Delphi
program TestShakerSort;   {$APPTYPE CONSOLE}   {.$DEFINE DYNARRAY} // remove '.' to compile with dynamic array   type TItem = Integer; // declare ordinal type for array item {$IFDEF DYNARRAY} TArray = array of TItem; // dynamic array {$ELSE} TArray = array[0..15] of TItem; // static array {$ENDIF}   procedure ShakerSort(var A: TArray); var Item: TItem; K, L, R, J: Integer;   begin L:= Low(A) + 1; R:= High(A); K:= High(A); repeat for J:= R downto L do begin if A[J - 1] > A[J] then begin Item:= A[J - 1]; A[J - 1]:= A[J]; A[J]:= Item; K:= J; end; end; L:= K + 1; for J:= L to R do begin if A[J - 1] > A[J] then begin Item:= A[J - 1]; A[J - 1]:= A[J]; A[J]:= Item; K:= J; end; end; R:= K - 1; until L > R; end;   var A: TArray; I: Integer;   begin {$IFDEF DYNARRAY} SetLength(A, 16); {$ENDIF} for I:= Low(A) to High(A) do A[I]:= Random(100); for I:= Low(A) to High(A) do Write(A[I]:3); Writeln; ShakerSort(A); for I:= Low(A) to High(A) do Write(A[I]:3); Writeln; Readln; end.
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
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 This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#jq
jq
def countingSort(min; max): . as $in | reduce range(0;length) as $i ( {}; ($in[$i]|tostring) as $s | .[$s] += 1 # courtesy of the fact that in jq, (null+1) is 1 ) | . as $hash # now construct the answer: | reduce range(min; max+1) as $i ( []; ($i|tostring) as $s | if $hash[$s] == null then . else reduce range(0; $hash[$s]) as $j (.; . + [$i]) end );
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
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 This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Julia
Julia
function countsort(a::Vector{<:Integer}) lo, hi = extrema(a) b = zeros(a) cnt = zeros(eltype(a), hi - lo + 1) for i in a cnt[i-lo+1] += 1 end z = 1 for i in lo:hi while cnt[i-lo+1] > 0 b[z] = i z += 1 cnt[i-lo+1] -= 1 end end return b end   v = rand(UInt8, 20) println("# unsorted bytes: $v\n -> sorted bytes: $(countsort(v))") v = rand(1:2 ^ 10, 20) println("# unsorted integers: $v\n -> sorted integers: $(countsort(v))")
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
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 Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#AutoHotkey
AutoHotkey
n2lexicog(n){ Arr := [], list := "" loop % n list .= A_Index "`n" Sort, list for k, v in StrSplit(Trim(list, "`n"), "`n") Arr.Push(v) return Arr }
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
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 Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#AWK
AWK
  # syntax: GAWK -f SORT_NUMBERS_LEXICOGRAPHICALLY.AWK # # sorting: # PROCINFO["sorted_in"] is used by GAWK # SORTTYPE is used by Thompson Automation's TAWK # BEGIN { prn(0) prn(1) prn(13) prn(9,10) prn(-11,+11) prn(-21) prn("",1) prn(+1,-1) exit(0) } function prn(n1,n2) { if (n1 <= 0 && n2 == "") { n2 = 1 } if (n2 == "") { n2 = n1 n1 = 1 } printf("%d to %d: %s\n",n1,n2,snl(n1,n2)) } function snl(start,stop, arr,i,str) { if (start == "") { return("error: start=blank") } if (start > stop) { return("error: start>stop") } for (i=start; i<=stop; i++) { arr[i] } PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 2 for (i in arr) { str = sprintf("%s%s ",str,i) } sub(/ $/,"",str) return(str) }  
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#BCPL
BCPL
get "libhdr"   // Sort 3 variables using a comparator. // X, Y and Z are pointers. let sort3(comp, x, y, z) be $( sort2(comp, x, y) sort2(comp, x, z) sort2(comp, y, z) $) and sort2(comp, x, y) be if comp(!x, !y) > 0 $( let t = !x  !x := !y  !y := t $)   // Integer and string comparators let intcomp(x, y) = x - y let strcomp(x, y) = valof $( for i=1 to min(x%0, y%0) unless x%i = y%i resultis intcomp(x%i, y%i) resultis intcomp(x%0, y%0) $) and min(x, y) = x < y -> x, y   // Run the function on both ints and strings let start() be $( printAndSort(writen, intcomp, 7444, -12, 0) printAndSort(writes, strcomp, "lions, tigers, and", "bears, oh my!", "(from the *"Wizard of OZ*")") $)   // Print the 3 values, sort them, and print them again and printAndSort(printfn, comp, x, y, z) be $( print3(printfn, x, y, z) ; writes("*N") sort3(comp, @x, @y, @z) print3(printfn, x, y, z) ; writes("------*N") $)   // Print 3 values given printing function and print3(printfn, x, y, z) be $( writes("X = ") ; printfn(x) ; wrch('*N') writes("Y = ") ; printfn(y) ; wrch('*N') writes("Z = ") ; printfn(z) ; wrch('*N') $)
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#C
C
  #include<string.h> #include<stdlib.h> #include<stdio.h>   #define MAX 3   int main() { char values[MAX][100],tempStr[100]; int i,j,isString=0; double val[MAX],temp;   for(i=0;i<MAX;i++){ printf("Enter %d%s value : ",i+1,(i==0)?"st":((i==1)?"nd":"rd")); fgets(values[i],100,stdin);   for(j=0;values[i][j]!=00;j++){ if(((values[i][j]<'0' || values[i][j]>'9') && (values[i][j]!='.' ||values[i][j]!='-'||values[i][j]!='+')) ||((values[i][j]=='.' ||values[i][j]=='-'||values[i][j]=='+')&&(values[i][j+1]<'0' || values[i][j+1]>'9'))) isString = 1; } }   if(isString==0){ for(i=0;i<MAX;i++) val[i] = atof(values[i]); }   for(i=0;i<MAX-1;i++){ for(j=i+1;j<MAX;j++){ if(isString==0 && val[i]>val[j]){ temp = val[j]; val[j] = val[i]; val[i] = temp; }   else if(values[i][0]>values[j][0]){ strcpy(tempStr,values[j]); strcpy(values[j],values[i]); strcpy(values[i],tempStr); } } }   for(i=0;i<MAX;i++) isString==1?printf("%c = %s",'X'+i,values[i]):printf("%c = %lf",'X'+i,val[i]);   return 0; }  
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#C
C
#include <stdlib.h> /* for qsort */ #include <string.h> /* for strlen */ #include <strings.h> /* for strcasecmp */   int mycmp(const void *s1, const void *s2) { const char *l = *(const char **)s1, *r = *(const char **)s2; size_t ll = strlen(l), lr = strlen(r);   if (ll > lr) return -1; if (ll < lr) return 1; return strcasecmp(l, r); }   int main() { const char *strings[] = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };   qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp); return 0; }
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detect and warn of at least two types of inconsistent indentation: inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces) inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces. Your code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units. You should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts. Your sort should not alter the type or size of the indentation units used in the input outline. (For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text [1] is available for inspection on Github). Tests Sort every level of the (4 space indented) outline below lexically, once ascending and once descending. zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Do the same with a tab-indented equivalent of the same outline. zeta gamma mu lambda kappa delta beta alpha theta iota epsilon The output sequence of an ascending lexical sort of each level should be: alpha epsilon iota theta zeta beta delta gamma kappa lambda mu The output sequence of a descending lexical sort of each level should be: zeta gamma mu lambda kappa delta beta alpha theta iota epsilon Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code. alpha epsilon iota theta zeta beta delta gamma kappa lambda mu zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Related tasks   Functional_coverage_tree   Display_an_outline_as_a_nested_table
#Phix
Phix
without javascript_semantics -- (tab chars are browser kryptonite) procedure print_children(sequence lines, children, string indent, bool bRev) sequence tags = custom_sort(lines,children) if bRev then tags = reverse(tags) end if for i=1 to length(tags) do integer ti = tags[i] printf(1,"%s%s\n",{indent,lines[ti][1]}) print_children(lines,lines[ti][$],lines[ti][2],bRev) end for end procedure constant spaced = """ zeta beta gamma lambda kappa mu delta alpha theta iota epsilon """, tabbed = substitute(spaced," ","\t"), confused = substitute_all(spaced,{" gamma"," kappa"},{"gamma","\t kappa"}), ragged = substitute_all(spaced,{" gamma","kappa"},{"gamma"," kappa"}), tests = {spaced,tabbed,confused,ragged}, names = "spaced,tabbed,confused,ragged" procedure test(sequence lines) sequence pi = {-1}, -- indents (to locate parents) pdx = {0}, -- indexes for "" children = {}, roots = {} for i=1 to length(lines) do string line = trim_tail(lines[i]), text = trim_head(line) integer indent = length(line)-length(text) -- remove any completed parents while length(pi) and indent<=pi[$] do pi = pi[1..$-1] pdx = pdx[1..$-1] end while integer parent = 0 if length(pi) then parent = pdx[$] if parent=0 then if indent!=0 then printf(1,"**invalid indent** (%s, line %d)\n\n",{text,i}) return end if roots &= i else if lines[parent][$]={} then lines[parent][2] = line[1..indent] elsif lines[parent][2]!=line[1..indent] then printf(1,"**inconsistent indent** (%s, line %d)\n\n",{text,i}) return end if lines[parent][$] &= i -- (update children) end if end if pi &= indent pdx &= i lines[i] = {text,"",children} end for printf(1,"ascending:\n") print_children(lines,roots,"",false) printf(1,"\ndescending:\n") print_children(lines,roots,"",true) printf(1,"\n") end procedure for t=1 to length(tests) do string name = split(names,",")[t] -- printf(1,"Test %d (%s):\n%s\n",{t,name,tests[t]}) printf(1,"Test %d (%s):\n",{t,name}) sequence lines = split(tests[t],"\n",no_empty:=true) test(lines) end for
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols binary   placesList = [String - "UK London", "US New York" - , "US Boston", "US Washington" - , "UK Washington", "US Birmingham" - , "UK Birmingham", "UK Boston" - ] sortedList = combSort(String[] Arrays.copyOf(placesList, placesList.length))   lists = [placesList, sortedList] loop ln = 0 to lists.length - 1 cl = lists[ln] loop ct = 0 to cl.length - 1 say cl[ct] end ct say end ln   return   method combSort(input = String[]) public constant binary returns String[]   swaps = isTrue gap = input.length loop label comb until gap = 1 & \swaps gap = int gap / 1.25 if gap < 1 then gap = 1 i_ = 0 swaps = isFalse loop label swaps until i_ + gap >= input.length if input[i_].compareTo(input[i_ + gap]) > 0 then do swap = input[i_] input[i_] = input[i_ + gap] input[i_ + gap] = swap swaps = isTrue end i_ = i_ + 1 end swaps end comb   return input   method isTrue public constant binary returns boolean return 1 == 1   method isFalse public constant binary returns boolean return \isTrue  
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Julia
Julia
function bogosort!(arr::AbstractVector) while !issorted(arr) shuffle!(arr) end return arr end   v = rand(-10:10, 10) println("# unordered: $v\n -> ordered: ", bogosort!(v))
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Kotlin
Kotlin
// version 1.1.2   const val RAND_MAX = 32768 // big enough for this   val rand = java.util.Random()   fun isSorted(a: IntArray): Boolean { val n = a.size if (n < 2) return true for (i in 1 until n) { if (a[i] < a[i - 1]) return false } return true }   fun shuffle(a: IntArray) { val n = a.size if (n < 2) return for (i in 0 until n) { val t = a[i] val r = rand.nextInt(RAND_MAX) % n a[i] = a[r] a[r] = t } }   fun bogosort(a: IntArray) { while (!isSorted(a)) shuffle(a) }   fun main(args: Array<String>) { val a = intArrayOf(1, 10, 9, 7, 3, 0) println("Before sorting : ${a.contentToString()}") bogosort(a) println("After sorting  : ${a.contentToString()}") }
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
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 A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Arendelle
Arendelle
< x > ( i , 0 ) ( sjt , 1; 0; 0 ) // swapped:0 / j:1 / temp:2 [ @sjt = 1 , ( sjt , 0 ) ( sjt[ 1 ] , +1 ) ( i , 0 ) [ @i < @x? - @sjt[ 1 ], { @x[ @i ] < @x[ @i + 1 ], ( sjt[ 2 ] , @x[ @i ] ) ( x[ @i ] , @x[ @i + 1 ] ) ( x[ @i + 1 ] , @sjt[ 2 ] ) ( sjt , 1 ) } ( i , +1 ) ] ] ( return , @x )
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
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 This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Factor
Factor
USING: kernel math sequences ; IN: rosetta-code.gnome-sort : inc-pos ( pos seq -- pos' seq ) [ 1 + ] dip ; inline : dec-pos ( pos seq -- pos' seq ) [ 1 - ] dip ; inline : take-two ( pos seq -- elt-at-pos-1 elt-at-pos ) [ dec-pos nth ] [ nth ] 2bi ; inline : need-swap? ( pos seq -- pos seq ? ) over 1 < [ f ] [ 2dup take-two > ] if ; : swap-back ( pos seq -- pos seq' ) [ take-two ] 2keep [ dec-pos set-nth ] 2keep [ set-nth ] 2keep ; : gnome-sort ( seq -- sorted-seq ) 1 swap [ 2dup length < ] [ 2dup [ need-swap? ] [ swap-back dec-pos ] while 2drop inc-pos ] while nip ;
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
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 of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#FreeBASIC
FreeBASIC
#define MAXNUM 100   Sub beadSort(bs() As Long) Dim As Long i, j = 1, lb = Lbound(bs), ub = Ubound(bs) Dim As Long poles(MAXNUM)   For i = 1 To ub For j = 1 To bs(i) poles(j) += 1 Next j Next i For j = 1 To ub bs(j) = 0 Next j For i = 1 To Ubound(poles) For j = 1 To poles(i) bs(j) += 1 Next j Next i End Sub   '--- Programa Principal --- Dim As Long i Dim As Ulong array(1 To 8) => {5, 3, 1, 7, 4, 1, 1, 20} Dim As Long a = Lbound(array), b = Ubound(array)   Randomize Timer   Print "unsort "; For i = a To b : Print Using "####"; array(i); : Next i   beadSort(array())   Print !"\n sort "; For i = a To b : Print Using "####"; array(i); : Next i   Print !"\n--- terminado, pulsa RETURN---" Sleep
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
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 This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#E
E
/** Cocktail sort (in-place) */ def cocktailSort(array) { def swapIndexes := 0..(array.size() - 2) def directions := [swapIndexes, swapIndexes.descending()] while (true) { for direction in directions { var swapped := false for a ? (array[a] > array[def b := a + 1]) in direction { def t := array[a] array[a] := array[b] array[b] := t swapped := true } if (!swapped) { return } } } }