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/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Standard_ML
Standard ML
fun quicksort [] = [] | quicksort (x::xs) = let val (left, right) = List.partition (fn y => y<x) xs in quicksort left @ [x] @ quicksort right end  
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
#360_Assembly
360 Assembly
* Comb sort 23/06/2016 COMBSORT CSECT USING COMBSORT,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) " LR R13,R15 " L R2,N n BCTR R2,0 n-1 ST R2,GAP gap=n-1 DO UNTIL=(CLC,GAP,EQ,=F'1',AND,CLI,SWAPS,EQ,X'00') repeat L R4,GAP gap | MH R4,=H'100' gap*100 | SRDA R4,32 . | D R4,=F'125' /125 | ST R5,GAP gap=int(gap/1.25) | IF CLC,GAP,LT,=F'1' if gap<1 then -----------+ | MVC GAP,=F'1' gap=1 | | ENDIF , end if <-----------------+ | MVI SWAPS,X'00' swaps=false | LA RI,1 i=1 | DO UNTIL=(C,R3,GT,N) do i=1 by 1 until i+gap>n ---+ | LR R7,RI i | | SLA R7,2 . | | LA R7,A-4(R7) r7=@a(i) | | LR R8,RI i | | A R8,GAP i+gap | | SLA R8,2 . | | LA R8,A-4(R8) r8=@a(i+gap) | | L R2,0(R7) temp=a(i) | | IF C,R2,GT,0(R8) if a(i)>a(i+gap) then ---+ | | MVC 0(4,R7),0(R8) a(i)=a(i+gap) | | | ST R2,0(R8) a(i+gap)=temp | | | MVI SWAPS,X'01' swaps=true | | | ENDIF , end if <-----------------+ | | LA RI,1(RI) i=i+1 | | LR R3,RI i | | A R3,GAP i+gap | | ENDDO , end do <---------------------+ | ENDDO , until gap=1 and not swaps <------+ LA R3,PG pgi=0 LA RI,1 i=1 DO WHILE=(C,RI,LE,N) do i=1 to n -------+ LR R1,RI i | SLA R1,2 . | L R2,A-4(R1) a(i) | XDECO R2,XDEC edit a(i) | MVC 0(4,R3),XDEC+8 output a(i) | LA R3,4(R3) pgi=pgi+4 | LA RI,1(RI) i=i+1 | ENDDO , end do <-----------+ XPRNT PG,L'PG print buffer L R13,4(0,R13) epilog LM R14,R12,12(R13) " XR R15,R15 " BR R14 exit A DC F'4',F'65',F'2',F'-31',F'0',F'99',F'2',F'83',F'782',F'1' DC F'45',F'82',F'69',F'82',F'104',F'58',F'88',F'112',F'89',F'74' N DC A((N-A)/L'A) number of items of a GAP DS F gap SWAPS DS X flag for swaps PG DS CL80 output buffer XDEC DS CL12 temp for edit YREGS RI EQU 6 i END COMBSORT
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Haskell
Haskell
import Data.Bool (bool)   circleSort :: Ord a => [a] -> [a] circleSort xs = if swapped then circleSort ks else ks where (swapped,ks) = go False xs (False,[])   go d [] sks = sks go d [x] (s,ks) = (s,x:ks) go d xs (s,ks) = let (st,_,ls,rs) = halve d s xs xs in go False ls (go True rs (st,ks))   halve d s (y:ys) (_:_:zs) = swap d y (halve d s ys zs) halve d s ys [] = (s,ys,[],[]) halve d s (y:ys) [_] = (s,ys,[y | e],[y | not e]) where e = y <= head ys   swap d x (s,y:ys,ls,rs) | bool (<=) (<) d x y = ( d || s,ys,x:ls,y:rs) | otherwise = (not d || s,ys,y:ls,x:rs)
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Swift
Swift
func quicksort<T where T : Comparable>(inout elements: [T], range: Range<Int>) { if (range.endIndex - range.startIndex > 1) { let pivotIndex = partition(&elements, range) quicksort(&elements, range.startIndex ..< pivotIndex) quicksort(&elements, pivotIndex+1 ..< range.endIndex) } }   func quicksort<T where T : Comparable>(inout elements: [T]) { quicksort(&elements, indices(elements)) }
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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program combSort64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeConstantesARM64.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data szMessSortOk: .asciz "Table sorted.\n" szMessSortNok: .asciz "Table not sorted !!!!!.\n" sMessResult: .asciz "Value  : @ \n" szCarriageReturn: .asciz "\n"   .align 4 #TableNumber: .quad 1,3,6,2,5,9,10,8,4,7 TableNumber: .quad 10,9,8,7,6,-5,4,3,2,1 .equ NBELEMENTS, (. - TableNumber) / 8 /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x0,qAdrTableNumber // address number table mov x1,0 mov x2,NBELEMENTS // number of élements bl combSort ldr x0,qAdrTableNumber // address number table bl displayTable   ldr x0,qAdrTableNumber // address number table mov x1,NBELEMENTS // number of élements bl isSorted // control sort cmp x0,1 // sorted ? beq 1f ldr x0,qAdrszMessSortNok // no !! error sort bl affichageMess b 100f 1: // yes ldr x0,qAdrszMessSortOk bl affichageMess 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 qAdrTableNumber: .quad TableNumber qAdrszMessSortOk: .quad szMessSortOk qAdrszMessSortNok: .quad szMessSortNok /******************************************************************/ /* control sorted table */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the number of elements > 0 */ /* x0 return 0 if not sorted 1 if sorted */ isSorted: stp x2,lr,[sp,-16]! // save registers stp x3,x4,[sp,-16]! // save registers mov x2,0 ldr x4,[x0,x2,lsl 3] 1: add x2,x2,1 cmp x2,x1 bge 99f ldr x3,[x0,x2, lsl 3] cmp x3,x4 blt 98f mov x4,x3 b 1b 98: mov x0,0 // not sorted b 100f 99: mov x0,1 // sorted 100: ldp x3,x4,[sp],16 // restaur 2 registers ldp x2,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* comb sort */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the first element */ /* x2 contains the number of element */ /* this routine use à factor to 1.28 see wikipedia for best factor */ combSort: 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 sub x9,x2,x1 // compute gap sub x2,x2,1 // compute end index n - 1 mov x7,100 1: // start loop 1 mul x9,x7,x9 // gap multiply by 100 lsr x9,x9,7 // divide by 128 cmp x9,0 mov x3,1 csel x9,x9,x3,ne mov x3,x1 // start index mov x8,0 // swaps 2: // start loop 2 add x4,x3,x9 // add gap to indice cmp x4,x2 bgt 4f ldr x5,[x0,x3,lsl 3] // load value A[j] ldr x6,[x0,x4,lsl 3] // load value A[j+1] cmp x6,x5 // compare value bge 3f str x6,[x0,x3,lsl 3] // if smaller inversion str x5,[x0,x4,lsl 3] mov x8,1 // swaps 3: add x3,x3,1 // increment index j b 2b   4: //bl displayTable cmp x9,1 // gap = 1 ? bne 1b // no loop cmp x8,1 // swaps ? beq 1b // yes -> loop 1   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 mov x2,x0 // table address mov x3,0 1: // loop display table ldr x0,[x2,x3,lsl 3] ldr x1,qAdrsZoneConv bl conversion10S // décimal conversion ldr x0,qAdrsMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message add x3,x3,1 cmp x3,NBELEMENTS - 1 ble 1b ldr x0,qAdrszCarriageReturn bl affichageMess mov x0,x2 100: 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/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#J
J
  circle_sort =: post power_of_2_length@pre NB. the main sorting verb power_of_2_length =: even_length_iteration^:_ NB. repeat while the answer changes even_length_iteration =: (<./ (,&$: |.) >./)@(-:@# ({. ,: |.@}.) ])^:(1<#) pre =: , (-~ >.&.(2&^.))@# # >./ NB. extend data to next power of 2 length post =: ({.~ #)~ NB. remove the extra data  
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Java
Java
import java.util.Arrays;   public class CircleSort {   public static void main(String[] args) { circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}); }   public static void circleSort(int[] arr) { if (arr.length > 0) do { System.out.println(Arrays.toString(arr)); } while (circleSortR(arr, 0, arr.length - 1, 0) != 0); }   private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) { if (lo == hi) return numSwaps;   int high = hi; int low = lo; int mid = (hi - lo) / 2;   while (lo < hi) { if (arr[lo] > arr[hi]) { swap(arr, lo, hi); numSwaps++; } lo++; hi--; }   if (lo == hi && arr[lo] > arr[hi + 1]) { swap(arr, lo, hi + 1); numSwaps++; }   numSwaps = circleSortR(arr, low, low + mid, numSwaps); numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);   return numSwaps; }   private static void swap(int[] arr, int idx1, int idx2) { int tmp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = tmp; } }
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Symsyn
Symsyn
    x : 23 : 15 : 99 : 146 : 3 : 66 : 71 : 5 : 23 : 73 : 19   quicksort param l r   l i r j ((l+r) shr 1) k x.k pivot   repeat if pivot > x.i + cmp + i goif endif   if pivot < x.j + cmp - j goif endif   if i <= j swap x.i x.j - j + i endif   if i <= j go repeat endif   if l < j save l r i j call quicksort l j restore l r i j endif   if i < r save l r i j call quicksort i r restore l r i j endif   return   start   ' original values : ' $r   call showvalues   call quicksort 0 10   ' sorted values : ' $r   call showvalues   stop   showvalues $s i if i <= 10 "$s ' ' x.i ' '" $s + i goif endif " $r $s " []   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
#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 CombSort(INT ARRAY a INT size) INT gap,i,tmp BYTE swaps   gap=size swaps=0 WHILE gap#1 OR swaps#0 DO gap=(gap*5)/4 IF gap<1 THEN gap=1 FI   i=0 swaps=0   WHILE i+gap<size DO IF a(i)>a(i+1) THEN tmp=a(i) a(i)=a(i+1) a(i+1)=tmp swaps=1 FI i==+1 OD OD RETURN   PROC Test(INT ARRAY a INT size) PrintE("Array before sort:") PrintArray(a,size) CombSort(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/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#jq
jq
def until(cond; next): def _until: if cond then . else (next|_until) end; _until;
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Tailspin
Tailspin
  templates quicksort @: []; $ -> # when <[](2..)> do def pivot: $(1); [ [ $(2..last)... -> \( when <..$pivot> do $ ! otherwise ..|@quicksort: $; \)] -> quicksort..., $pivot, $@ -> quicksort... ] ! otherwise $ ! end quicksort   [4,5,3,8,1,2,6,7,9,8,5] -> quicksort -> !OUT::write  
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
#ActionScript
ActionScript
function combSort(input:Array) { var gap:uint = input.length; var swapped:Boolean = false; while(gap > 1 || swapped) { gap /= 1.25; swapped = false; for(var i:uint = 0; i + gap < input.length; i++) { if(input[i] > input[i+gap]) { var tmp = input[i]; input[i] = input[i+gap]; input[i+gap]=tmp; swapped = true; } } } return input; }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Julia
Julia
function _ciclesort!(arr::Vector, lo::Int, hi::Int, swaps::Int) lo == hi && return swaps high = hi low = lo mid = (hi - lo) ÷ 2 while lo < hi if arr[lo] > arr[hi] arr[lo], arr[hi] = arr[hi], arr[lo] swaps += 1 end lo += 1 hi -= 1 end if lo == hi if arr[lo] > arr[hi+1] arr[lo], arr[hi+1] = arr[hi+1], arr[lo] swaps += 1 end end swaps = _ciclesort!(arr, low, low + mid, swaps) swaps = _ciclesort!(arr, low + mid + 1, high, swaps) return swaps end   function ciclesort!(arr::Vector) while !iszero(_ciclesort!(arr, 1, endof(arr), 0)) end return arr end   v = rand(10) println("# $v\n -> ", ciclesort!(v))
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Kotlin
Kotlin
// version 1.1.0   fun<T: Comparable<T>> circleSort(array: Array<T>, lo: Int, hi: Int, nSwaps: Int): Int { if (lo == hi) return nSwaps   fun swap(array: Array<T>, i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp }   var high = hi var low = lo val mid = (hi - lo) / 2 var swaps = nSwaps while (low < high) { if (array[low] > array[high]) { swap(array, low, high) swaps++ } low++ high-- } if (low == high) if (array[low] > array[high + 1]) { swap(array, low, high + 1) swaps++ } swaps = circleSort(array, lo, lo + mid, swaps) swaps = circleSort(array, lo + mid + 1, hi, swaps) return swaps }   fun main(args: Array<String>) { val array = arrayOf(6, 7, 8, 9, 2, 5, 3, 4, 1) println("Original: ${array.asList()}") while (circleSort(array, 0, array.size - 1, 0) != 0) ; // empty statement println("Sorted  : ${array.asList()}") println() val array2 = arrayOf("the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog") println("Original: ${array2.asList()}") while (circleSort(array2, 0, array2.size - 1, 0) != 0) ; println("Sorted  : ${array2.asList()}") }
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Tcl
Tcl
package require Tcl 8.5   proc quicksort {m} { if {[llength $m] <= 1} { return $m } set pivot [lindex $m 0] set less [set equal [set greater [list]]] foreach x $m { lappend [expr {$x < $pivot ? "less" : $x > $pivot ? "greater" : "equal"}] $x } return [concat [quicksort $less] $equal [quicksort $greater]] }   puts [quicksort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9
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
#Ada
Ada
with Ada.Text_IO; procedure Comb_Sort is generic type Element_Type is private; type Index_Type is range <>; type Array_Type is array (Index_Type range <>) of Element_Type; with function ">" (Left, Right : Element_Type) return Boolean is <>; with function "+" (Left : Index_Type; Right : Natural) return Index_Type is <>; with function "-" (Left : Index_Type; Right : Natural) return Index_Type is <>; procedure Comb_Sort (Data: in out Array_Type);   procedure Comb_Sort (Data: in out Array_Type) is procedure Swap (Left, Right : in Index_Type) is Temp : Element_Type := Data(Left); begin Data(Left)  := Data(Right); Data(Right) := Temp; end Swap; Gap : Natural := Data'Length; Swap_Occured : Boolean; begin loop Gap := Natural (Float(Gap) / 1.25 - 0.5); if Gap < 1 then Gap := 1; end if; Swap_Occured := False; for I in Data'First .. Data'Last - Gap loop if Data (I) > Data (I+Gap) then Swap (I, I+Gap); Swap_Occured := True; end if; end loop; exit when Gap = 1 and not Swap_Occured; end loop; end Comb_Sort;   type Integer_Array is array (Positive range <>) of Integer; procedure Int_Comb_Sort is new Comb_Sort (Integer, Positive, Integer_Array); Test_Array : Integer_Array := (1, 3, 256, 0, 3, 4, -1); begin Int_Comb_Sort (Test_Array); for I in Test_Array'Range loop Ada.Text_IO.Put (Integer'Image (Test_Array (I))); end loop; Ada.Text_IO.New_Line; end Comb_Sort;
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Lua
Lua
-- Perform one iteration of a circle sort function innerCircle (t, lo, hi, swaps) if lo == hi then return swaps end local high, low, mid = hi, lo, math.floor((hi - lo) / 2) while lo < hi do if t[lo] > t[hi] then t[lo], t[hi] = t[hi], t[lo] swaps = swaps + 1 end lo = lo + 1 hi = hi - 1 end if lo == hi then if t[lo] > t[hi + 1] then t[lo], t[hi + 1] = t[hi + 1], t[lo] swaps = swaps + 1 end end swaps = innerCircle(t, low, low + mid, swaps) swaps = innerCircle(t, low + mid + 1, high, swaps) return swaps end   -- Keep sorting the table until an iteration makes no swaps function circleSort (t) while innerCircle(t, 1, #t, 0) > 0 do end end   -- Main procedure local array = {6, 7, 8, 9, 2, 5, 3, 4, 1} circleSort(array) print(table.concat(array, " "))
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#TypeScript
TypeScript
  /** Generic quicksort function using typescript generics. Follows quicksort as done in CLRS. */ export type Comparator<T> = (o1: T, o2: T) => number;     export function quickSort<T>(array: T[], compare: Comparator<T>) { if (array.length <= 1 || array == null) { return; } sort(array, compare, 0, array.length - 1); }   function sort<T>( array: T[], compare: Comparator<T>, low: number, high: number) { if (low < high) { const partIndex = partition(array, compare, low, high); sort(array, compare, low, partIndex - 1); sort(array, compare, partIndex + 1, high); } }   function partition<T>( array: T[], compare: Comparator<T>, low: number, high: number): number { const pivot: T = array[high]; let i: number = low - 1; for (let j = low; j <= high - 1; j++) { if (compare(array[j], pivot) == -1) { i = i + 1; swap(array, i, j) } } if (compare(array[high], array[i + 1]) == -1) { swap(array, i + 1, high); } return i + 1; }   function swap<T>(array: T[], i: number, j: number) { const newJ: T = array[i]; array[i] = array[j]; array[j] = newJ; }   export function testQuickSort(): void { function numberComparator(o1: number, o2: number): number { if (o1 < o2) { return -1; } else if (o1 == o2) { return 0; } return 1; } let tests: number[][] = [ [], [1], [2, 1], [-1, 2, -3], [3, 16, 8, -5, 6, 4], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5] ];   for (let testArray of tests) { quickSort(testArray, numberComparator); console.log(testArray); } }  
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
#ALGOL_68
ALGOL 68
BEGIN # comb sort # PR read "rows.incl.a68" PR # include row (array) utilities - SHOW is used to display the array # # comb-sorts in-place the array of integers input # PROC comb sort = ( REF[]INT input )VOID: IF INT input size = ( UPB input - LWB input ) + 1; input size > 1 THEN # more than one element, so must sort # INT gap := input size; # initial gap is the whole array size # BOOL swapped := TRUE; WHILE gap /= 1 OR swapped DO # update the gap value for a next comb # gap := ENTIER ( gap / 1.25 ); IF gap < 1 THEN # ensure the gap is at least 1 # gap := 1 FI; INT i := LWB input; swapped := FALSE; # a single "comb" over the input list # FOR i FROM LWB input WHILE i + gap <= UPB input DO INT t = input[ i ]; INT i gap = i + gap; IF t > input[ i gap ] THEN # need to swap out-of-order items # input[ i ] := input[ i gap ]; input[ i gap ] := t; swapped := TRUE # Flag a swap has occurred, so the list is not guaranteed sorted yet # FI OD OD FI # comb sort # ; # test # [ 1 : 7 ]INT data := ( 9, -4, 0, 2, 3, 77, 1 ); # data to sort # SHOW data; comb sort( data ); print( ( " -> " ) ); SHOW data END
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[CircleSort, NestedCircleSort] CircleSort[d_List, l_, h_] := Module[{high, low, mid, lo = l, hi = h, data = d}, If[lo == hi, Return[data]]; high = hi; low = lo; mid = Floor[(hi - lo)/2]; While[lo < hi, If[data[[lo]] > data[[hi]], data[[{lo, hi}]] //= Reverse; ]; lo++; hi-- ]; If[lo == hi, If[data[[lo]] > data[[hi + 1]], data[[{lo, hi + 1}]] //= Reverse; ] ]; data = CircleSort[data, low, low + mid]; data = CircleSort[data, low + mid + 1, high]; data ] NestedCircleSort[{}] := {} NestedCircleSort[d_List] := FixedPoint[CircleSort[#, 1, Length[#]] &, d] NestedCircleSort[Echo@{6, 7, 8, 9, 2, 5, 3, 4, 1}] NestedCircleSort[Echo@{6, 7, 8, 2, 5, 3, 4, 1}] NestedCircleSort[Echo@{6, 2, 5, 7, 3, 4, 1}] NestedCircleSort[Echo@{4, 6, 3, 5, 2, 1}] NestedCircleSort[Echo@{1, 2, 3, 4, 5}] NestedCircleSort[Echo@{2, 4, 3, 1}] NestedCircleSort[Echo@{2, 3, 1}] NestedCircleSort[Echo@{2, 1}] NestedCircleSort[Echo@{1}] NestedCircleSort[Echo@{}]
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Nim
Nim
proc innerCircleSort[T](a: var openArray[T], lo, hi, swaps: int): int = var localSwaps: int = swaps var localHi: int = hi var localLo: int = lo if localLo == localHi: return swaps   var `high` = localHi var `low` = localLo var mid = (localHi - localLo) div 2   while localLo < localHi: if a[localLo] > a[localHi]: swap a[localLo], a[localHi] inc localSwaps inc localLo dec localHi if localLo == localHi: if a[localLo] > a[localHi + 1]: swap a[localLo], a[localHi + 1] inc localSwaps   localswaps = a.innerCircleSort(`low`, `low` + mid, localSwaps) localSwaps = a.innerCircleSort(`low` + mid + 1, `high`, localSwaps) result = localSwaps   proc circleSort[T](a: var openArray[T]) = while a.innerCircleSort(0, a.high, 0) != 0: discard   var arr = @[@[6, 7, 8, 9, 2, 5, 3, 4, 1], @[2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]]   for i in 0..arr.high: echo "Original: ", $arr[i] arr[i].circleSort() echo "Sorted: ", $arr[i], if i != arr.high: "\n" else: ""
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#uBasic.2F4tH
uBasic/4tH
PRINT "Quick sort:" n = FUNC (_InitArray) PROC _ShowArray (n) PROC _Quicksort (n) PROC _ShowArray (n) PRINT   END     _InnerQuick PARAM(2) LOCAL(4)   IF b@ < 2 THEN RETURN f@ = a@ + b@ - 1 c@ = a@ e@ = f@ d@ = @((c@ + e@) / 2)   DO DO WHILE @(c@) < d@ c@ = c@ + 1 LOOP   DO WHILE @(e@) > d@ e@ = e@ - 1 LOOP   IF c@ - 1 < e@ THEN PROC _Swap (c@, e@) c@ = c@ + 1 e@ = e@ - 1 ENDIF   UNTIL c@ > e@ LOOP   IF a@ < e@ THEN PROC _InnerQuick (a@, e@ - a@ + 1) IF c@ < f@ THEN PROC _InnerQuick (c@, f@ - c@ + 1) RETURN     _Quicksort PARAM(1) ' Quick sort PROC _InnerQuick (0, a@) RETURN     _Swap PARAM(2) ' Swap two array elements PUSH @(a@) @(a@) = @(b@) @(b@) = POP() RETURN     _InitArray ' Init example array PUSH 4, 65, 2, -31, 0, 99, 2, 83, 782, 1   FOR i = 0 TO 9 @(i) = POP() NEXT   RETURN (i)     _ShowArray PARAM (1) ' Show array subroutine FOR i = 0 TO a@-1 PRINT @(i), NEXT   PRINT 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
#ALGOL_W
ALGOL W
begin % comb sort %  % comb-sorts in-place the array of integers input with bounds lb :: ub % procedure combSort ( integer array input ( * )  ; integer value lb, ub ) ; begin integer inputSize, gap, i; inputSize := ( ub - lb ) + 1; if inputSize > 1 then begin  % more than one element, so must sort % logical swapped; gap  := inputSize; % initial gap is the whole array size % swapped := true; while gap not = 1 or swapped do begin  % update the gap value for a next comb % gap := entier( gap / 1.25 ); if gap < 1 then begin  % ensure the gap is at least 1 % gap := 1 end if_gap_lt_1 ; swapped := false;  % a single "comb" over the input list % i := lb; while i + gap <= ub do begin integer t, iGap; t  := input( i ); iGap := i + gap; if t > input( iGap ) then begin  % need to swap out-of-order items % input( i ) := input( iGap ); input( iGap ) := t; swapped := true % Flag a swap has occurred, so the list is not guaranteed sorted yet % end if_t_gt_input__iGap ; i := i + 1 end while_i_plus_gap_le_ub end while_gap_ne_1_or_swapped end if_inputSize_gt_1 end combSort ; begin % test % integer array data ( 1 :: 7 ); integer dPos; dPos := 0; for v := 9, -4, 0, 2, 3, 77, 1 do begin dPos := dPos + 1; data( dPos ) := v end; for i := 1 until 7 do writeon( i_w := 1, s_w := 0, " ", data( i ) ); combSort( data, 1, 7 ); writeon( ( " -> " ) ); for i := 1 until 7 do writeon( i_w := 1, s_w := 0, " ", data( i ) ) end end.
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Objeck
Objeck
class CircleSort { function : Main(args : String[]) ~ Nil { circleSort([2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]); }   function : circleSort(arr : Int[]) ~ Nil { if(arr->Size() > 0) { do { arr->ToString()->PrintLine(); } while(CircleSort(arr, 0, arr->Size() - 1, 0) <> 0); }; }   function : CircleSort( arr : Int[], lo : Int, hi : Int, num_swaps : Int) ~ Int { if(lo = hi) { return num_swaps; };     high := hi; low := lo; mid := (hi - lo) / 2;   while (lo < hi) { if(arr[lo] > arr[hi]) { Swap(arr, lo, hi); num_swaps++; }; lo++; hi--; };   if(lo = hi & arr[lo] > arr[hi + 1]) { Swap(arr, lo, hi + 1); num_swaps++; };   num_swaps := CircleSort(arr, low, low + mid, num_swaps); num_swaps := CircleSort(arr, low + mid + 1, high, num_swaps);   return num_swaps; }   function : Swap(arr : Int[], idx1 : Int, idx2 : Int) ~ Nil { tmp := arr[idx1]; arr[idx1] := arr[idx2]; arr[idx2] := tmp; } }  
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#UnixPipes
UnixPipes
split() { (while read n ; do test $1 -gt $n && echo $n > $2 || echo $n > $3 done) }   qsort() { (read p; test -n "$p" && ( lc="1.$1" ; gc="2.$1" split $p >(qsort $lc >$lc) >(qsort $gc >$gc); cat $lc <(echo $p) $gc rm -f $lc $gc; )) }   cat to.sort | qsort
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
#AppleScript
AppleScript
-- Comb sort with insertion sort finish. -- Comb sort algorithm: Włodzimierz Dobosiewicz and Artur Borowy, 1980. Stephen Lacey and Richard Box, 1991.   on combSort(theList, l, r) -- Sort items l thru r of theLIst. set listLen to (count theList) if (listLen < 2) then return -- 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}   script o property lst : theList end script   -- This implementation performs fastest with a comb gap divisor of 1.4 -- and the insertion sort taking over when the gap's down to 8 or less. set divisor to 1.4 set gap to (r - l + 1) div divisor repeat while (gap > 8) repeat with i from l to (r - gap) set j to i + gap set lv to o's lst's item i set rv to o's lst's item j if (lv > rv) then set o's lst's item i to rv set o's lst's item j to lv end if end repeat set gap to gap div divisor end repeat   insertionSort(theList, l, r)   return -- nothing. end combSort   on insertionSort(theList, l, r) -- Sort items l thru r of theList. set listLength to (count theList) if (listLength < 2) then return if (l < 0) then set l to listLength + l + 1 if (r < 0) then set r to listLength + r + 1 if (l > r) then set {l, r} to {r, l}   script o property lst : theList end script   set highestSoFar to o's lst's item l set rv to o's lst's item (l + 1) if (highestSoFar > rv) then set o's lst's item l to rv else set highestSoFar to rv end if repeat with j from (l + 2) to r set rv to o's lst's item j if (highestSoFar > rv) then repeat with i from (j - 2) to l by -1 set lv to o's lst's item i if (lv > rv) then set o's lst's item (i + 1) to lv else set i to i + 1 exit repeat end if end repeat set o's lst's item i to rv else set o's lst's item (j - 1) to highestSoFar set highestSoFar to rv end if end repeat set o's lst's item r to highestSoFar   return -- nothing. end insertionSort   -- Demo: local aList set aList to {7, 56, 70, 22, 94, 42, 5, 25, 54, 90, 29, 65, 87, 27, 4, 5, 86, 8, 2, 30, 87, 12, 85, 86, 7} combSort(aList, 1, -1) -- Sort items 1 thru -1 of aList. aList
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#PARI.2FGP
PARI/GP
circlesort(v)= { local(v=v); \\ share with cs while (cs(1, #v),); v; } cs(lo, hi)= { if (lo == hi, return (0)); my(high=hi,low=lo,mid=(hi-lo)\2,swaps); while (lo < hi, if (v[lo] > v[hi], [v[lo],v[hi]]=[v[hi],v[lo]]; swaps++ ); lo++; hi-- ); if (lo==hi && v[lo] > v[hi+1], [v[lo],v[hi+1]]=[v[hi+1],v[lo]]; swaps++ ); swaps + cs(low,low+mid) + cs(low+mid+1,high); } print(example=[6,7,8,9,2,5,3,4,1]); print(circlesort(example));
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Ursala
Ursala
#import nat   quicksort "p" = ~&itB^?a\~&a ^|WrlT/~& "p"*|^\~& "p"?hthPX/~&th ~&h   #cast %nL   example = quicksort(nleq) <694,1377,367,506,3712,381,1704,1580,475,1872>
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
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program combSort.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data szMessSortOk: .asciz "Table sorted.\n" szMessSortNok: .asciz "Table not sorted !!!!!.\n" sMessResult: .asciz "Value  : @ \n" szCarriageReturn: .asciz "\n"   .align 4 #TableNumber: .int 1,3,6,2,5,9,10,8,4,7 TableNumber: .int 10,9,8,7,6,5,4,3,2,1 .equ NBELEMENTS, (. - TableNumber) / 4 /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   1: ldr r0,iAdrTableNumber @ address number table mov r1,#0 mov r2,#NBELEMENTS @ number of élements bl combSort ldr r0,iAdrTableNumber @ address number table bl displayTable   ldr r0,iAdrTableNumber @ address number table mov r1,#NBELEMENTS @ number of élements bl isSorted @ control sort cmp r0,#1 @ sorted ? beq 2f ldr r0,iAdrszMessSortNok @ no !! error sort bl affichageMess b 100f 2: @ yes ldr r0,iAdrszMessSortOk bl affichageMess 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResult: .int sMessResult iAdrTableNumber: .int TableNumber iAdrszMessSortOk: .int szMessSortOk iAdrszMessSortNok: .int szMessSortNok /******************************************************************/ /* control sorted table */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the number of elements > 0 */ /* r0 return 0 if not sorted 1 if sorted */ isSorted: push {r2-r4,lr} @ save registers mov r2,#0 ldr r4,[r0,r2,lsl #2] 1: add r2,#1 cmp r2,r1 movge r0,#1 bge 100f ldr r3,[r0,r2, lsl #2] cmp r3,r4 movlt r0,#0 blt 100f mov r4,r3 b 1b 100: pop {r2-r4,lr} bx lr @ return /******************************************************************/ /* comb Sort */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the first element */ /* r2 contains the number of element */ /* this routine use à factor to 1.28 see wikipedia for best factor */ combSort: push {r1-r9,lr} @ save registers sub r9,r2,r1 @ compute gap sub r2,r2,#1 @ compute end index = n - 1 mov r7,#100 1: @ start loop 1 mul r9,r7,r9 @ gap multiply by 100 lsrs r9,#7 @ divide by 128 equi * 0,78125 equi divide by 1,28 moveq r9,#1 @ if gap = 0 -> gap = 1 mov r8,#0 @ swaps mov r3,r1 @ indice 2: @ start loop 2 add r4,r3,r9 cmp r4,r2 @ end ? bgt 3f ldr r5,[r0,r3,lsl #2] @ load value A[j] ldr r6,[r0,r4,lsl #2] @ load value A[j+1] cmp r6,r5 @ compare value strlt r6,[r0,r3,lsl #2] @ if smaller inversion strlt r5,[r0,r4,lsl #2] movlt r8,#1 @ swaps = 1 add r3,#1 @ increment indice b 2b @ loop 2   3: @ bl displayTable cmp r9,#1 @ gap = 1 ? bne 1b cmp r8,#1 @ swaps ? beq 1b @ yes -> loop 1   100: pop {r1-r9,lr} bx lr @ return   /******************************************************************/ /* Display table elements */ /******************************************************************/ /* r0 contains the address of table */ displayTable: push {r0-r3,lr} @ save registers mov r2,r0 @ table address mov r3,#0 1: @ loop display table ldr r0,[r2,r3,lsl #2] ldr r1,iAdrsZoneConv @ bl conversion10S @ décimal conversion ldr r0,iAdrsMessResult ldr r1,iAdrsZoneConv @ insert conversion bl strInsertAtCharInc bl affichageMess @ display message add r3,#1 cmp r3,#NBELEMENTS - 1 ble 1b ldr r0,iAdrszCarriageReturn bl affichageMess 100: pop {r0-r3,lr} bx lr iAdrsZoneConv: .int sZoneConv /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Pascal
Pascal
  { source file name on linux is ./p.p   -*- mode: compilation; default-directory: "/tmp/" -*- Compilation started at Sat Mar 11 23:55:25   a=./p && pc $a.p && $a Free Pascal Compiler version 3.0.0+dfsg-8 [2016/09/03] for x86_64 Copyright (c) 1993-2015 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling ./p.p Linking p /usr/bin/ld.bfd: warning: link.res contains output sections; did you forget -T? 56 lines compiled, 0.0 sec 1 2 3 4 5 6 7 8 9   Compilation finished at Sat Mar 11 23:55:25 }   program sort;   var a : array[0..999] of integer; i : integer;   procedure circle_sort(var a : array of integer; left : integer; right : integer); var swaps : integer;   procedure csinternal(var a : array of integer; left : integer; right : integer; var swaps : integer); var lo, hi, mid : integer; t : integer; begin if left < right then begin lo := left; hi := right; while lo < hi do begin if a[hi] < a[lo] then begin t := a[lo]; a[lo] := a[hi]; a[hi] := t; swaps := swaps + 1; end; lo := lo + 1; hi := hi - 1; end; if (lo = hi) and (a[lo+1] < a[lo]) then begin t := a[lo]; a[lo] := a[lo+1]; a[lo+1] := t; swaps := swaps + 1; end; mid := trunc((hi + lo) / 2); csinternal(a, left, mid, swaps); csinternal(a, mid + 1, right, swaps) end end;   begin; swaps := 1; while (0 < swaps) do begin swaps := 0; csinternal(a, left, right, swaps); end end;   begin { generating polynomial coefficients computed in j: 6 7 8 9 2 5 3 4 1x %. ^/~i.9x are 6 29999r280 _292519r1120 70219r288 _73271r640 10697r360 _4153r960 667r2016 _139r13440 } a[1]:=6;a[2]:=7;a[3]:=8;a[4]:=9;a[5]:=2;a[6]:=5;a[7]:=3;a[8]:=4;a[9]:=1; circle_sort(a,1,9); for i := 1 to 9 do write(a[i], ' '); writeln(); end.  
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#V
V
[qsort [joinparts [p [*l1] [*l2] : [*l1 p *l2]] view]. [split_on_first uncons [>] split]. [small?] [] [split_on_first [l1 l2 : [l1 qsort l2 qsort joinparts]] view i] ifte].
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
#Arturo
Arturo
combSort: function [items][ a: new items gap: size a swapped: true   while [or? gap > 1 swapped][ gap: (gap * 10) / 13 if or? gap=9 gap=10 -> gap: 11 if gap<1 -> gap: 1 swapped: false i: 0 loop gap..dec size items 'j [ if a\[i] > a\[j] [ tmp: a\[i] a\[i]: a\[j] a\[j]: tmp swapped: true ] i: i + 1 ] ] return a ]   print combSort [3 1 2 8 5 7 9 4 6]
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.
#11l
11l
F is_sorted(data) R all((0 .< data.len - 1).map(i -> @data[i] <= @data[i + 1]))   F bogosort(&data) L !is_sorted(data) random:shuffle(&data)   V arr = [2, 1, 3] bogosort(&arr) print(arr)
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Perl
Perl
sub circlesort { our @x; local *x = shift; my($beg,$end) = @_;   my $swaps = 0; if ($beg < $end) { my $lo = $beg; my $hi = $end; while ($lo < $hi) { if ($x[$lo] > $x[$hi]) { # 'gt' here for string comparison @x[$lo,$hi] = @x[$hi,$lo]; ++$swaps; } ++$hi if --$hi == ++$lo } $swaps += circlesort(\@x, $beg, $hi); $swaps += circlesort(\@x, $lo, $end); } $swaps; }   my @a = <16 35 -64 -29 46 36 -1 -99 20 100 59 26 76 -78 39 85 -7 -81 25 88>; while (circlesort(\@a, 0, $#a)) { print join(' ', @a), "\n" }
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#VBA
VBA
Public Sub Quick(a() As Variant, last As Integer) ' quicksort a Variant array (1-based, numbers or strings) Dim aLess() As Variant Dim aEq() As Variant Dim aGreater() As Variant Dim pivot As Variant Dim naLess As Integer Dim naEq As Integer Dim naGreater As Integer   If last > 1 Then 'choose pivot in the middle of the array pivot = a(Int((last + 1) / 2)) 'construct arrays naLess = 0 naEq = 0 naGreater = 0 For Each el In a() If el > pivot Then naGreater = naGreater + 1 ReDim Preserve aGreater(1 To naGreater) aGreater(naGreater) = el ElseIf el < pivot Then naLess = naLess + 1 ReDim Preserve aLess(1 To naLess) aLess(naLess) = el Else naEq = naEq + 1 ReDim Preserve aEq(1 To naEq) aEq(naEq) = el End If Next 'sort arrays "less" and "greater" Quick aLess(), naLess Quick aGreater(), naGreater 'concatenate P = 1 For i = 1 To naLess a(P) = aLess(i): P = P + 1 Next For i = 1 To naEq a(P) = aEq(i): P = P + 1 Next For i = 1 To naGreater a(P) = aGreater(i): P = P + 1 Next End If End Sub   Public Sub QuicksortTest() Dim a(1 To 26) As Variant   'populate a with numbers in descending order, then sort For i = 1 To 26: a(i) = 26 - i: Next Quick a(), 26 For i = 1 To 26: Debug.Print a(i);: Next Debug.Print 'now populate a with strings in descending order, then sort For i = 1 To 26: a(i) = Chr$(Asc("z") + 1 - i) & "-stuff": Next Quick a(), 26 For i = 1 To 26: Debug.Print a(i); " ";: Next Debug.Print End Sub
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
#AutoHotkey
AutoHotkey
List1 = 23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78 List2 = 88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70   List2Array(List1, "MyArray") CombSort("MyArray") MsgBox, % List1 "`n" Array2List("MyArray")   List2Array(List2, "MyArray") CombSort("MyArray") MsgBox, % List2 "`n" Array2List("MyArray")       ;--------------------------------------------------------------------------- CombSort(Array) { ; CombSort of Array %Array%, length = %Array%0 ;--------------------------------------------------------------------------- Gap := %Array%0 While Gap > 1 Or Swaps { If (Gap > 1) Gap := 4 * Gap // 5 i := Swaps := False While (j := ++i + Gap) <= %Array%0 { If (%Array%%i% > %Array%%j%) { Swaps := True %Array%%i% := (%Array%%j% "", %Array%%j% := %Array%%i%) } } } }       ;--------------------------------------------------------------------------- List2Array(List, Array) { ; creates an array from a comma separated list ;--------------------------------------------------------------------------- global StringSplit, %Array%, List, `, }       ;--------------------------------------------------------------------------- Array2List(Array) { ; returns a comma separated list from an array ;--------------------------------------------------------------------------- Loop, % %Array%0 List .= (A_Index = 1 ? "" : ",") %Array%%A_Index% Return, List }
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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program bogosort64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc" /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .asciz "Value  : @ \n" szCarriageReturn: .asciz "\n"   .align 4 qGraine: .quad 123456 TableNumber: .quad 1,2,3,4,5,6,7,8,9,10 .equ NBELEMENTS, (. - TableNumber) / 8   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program   1: ldr x0,qAdrTableNumber // address number table mov x1,#NBELEMENTS // number of élements bl knuthShuffle // table display elements ldr x0,qAdrTableNumber // address number table mov x1,#NBELEMENTS // number of élements bl displayTable   ldr x0,qAdrTableNumber // address number table mov x1,#NBELEMENTS // number of élements bl isSorted // control sort cmp x0,#1 // sorted ? bne 1b // no -> loop     100: // standard end of the program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc #0 // perform the system call   qAdrszCarriageReturn: .quad szCarriageReturn qAdrsMessResult: .quad sMessResult qAdrTableNumber: .quad TableNumber   /******************************************************************/ /* control sorted table */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the number of elements > 0 */ /* x0 return 0 if not sorted 1 if sorted */ isSorted: stp x2,lr,[sp,-16]! // save registers stp x3,x4,[sp,-16]! // save registers mov x2,#0 ldr x4,[x0,x2,lsl #3] // load A[0] 1: add x2,x2,#1 cmp x2,x1 // end ? bge 99f ldr x3,[x0,x2, lsl #3] // load A[i] cmp x3,x4 // compare A[i],A[i-1] blt 98f // smaller -> error -> return mov x4,x3 // no -> A[i-1] = A[i] b 1b // and loop 98: mov x0,#0 // error b 100f 99: mov x0,#1 // ok -> return 100: 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 */ /* x1 contains elements number */ displayTable: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers mov x2,x0 // table address mov x4,x1 // elements number mov x3,#0 1: // loop display table ldr x0,[x2,x3,lsl #3] ldr x1,qAdrsZoneConv bl conversion10 // décimal conversion ldr x0,qAdrsMessResult ldr x1,qAdrsZoneConv // insert conversion bl strInsertAtCharInc bl affichageMess // display message add x3,x3,#1 cmp x3,x4 // end ? blt 1b // no -> loop ldr x0,qAdrszCarriageReturn bl affichageMess 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrsZoneConv: .quad sZoneConv /******************************************************************/ /* shuffle game */ /******************************************************************/ /* x0 contains boxs address */ /* x1 contains elements number */ knuthShuffle: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers mov x5,x0 // save table address mov x2,#0 // start index 1: mov x0,x2 // generate aleas bl genereraleas ldr x3,[x5,x2,lsl #3] // swap number on the table ldr x4,[x5,x0,lsl #3] str x4,[x5,x2,lsl #3] str x3,[x5,x0,lsl #3] add x2,x2,1 // next number cmp x2,x1 // end ? blt 1b // no -> loop   100: 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 /***************************************************/ /* Generation random number */ /***************************************************/ /* x0 contains limit */ genereraleas: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers ldr x1,qAdrqGraine ldr x2,[x1] ldr x3,qNbDep1 mul x2,x3,x2 ldr x3,qNbDep2 add x2,x2,x3 str x2,[x1] // maj de la graine pour l appel suivant cmp x0,#0 beq 100f udiv x3,x2,x0 msub x0,x3,x0,x2 // résult = remainder   100: // end function ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrqGraine: .quad qGraine qNbDep1: .quad 0x0019660d qNbDep2: .quad 0x3c6ef35f /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Phix
Phix
with javascript_semantics sequence array function circle_sort_inner(integer lo, hi, swaps, level=1) if lo!=hi then integer high := hi, low := lo, mid := floor((high-low)/2) while lo <= hi do hi += (lo=hi) object alo = array[lo], ahi = array[hi] if alo > ahi then array[lo] = ahi array[hi] = alo printf(1,"%V level %d, low %d, high %d\n",{array,level,low,high}) swaps += 1 end if lo += 1 hi -= 1 end while swaps = circle_sort_inner(low,low+mid,swaps,level+1) swaps = circle_sort_inner(low+mid+1,high,swaps,level+1) end if return swaps end function procedure circle_sort() printf(1,"%V <== (initial)\n",{array}) while circle_sort_inner(1, length(array), 0) do ?"loop" end while printf(1,"%V <== (sorted)\n",{array}) end procedure array = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3} --array = {-4,-1,1,0,5,-7,-2,4,-6,-3,2,6,3,7,-5} --array = {6, 7, 8, 9, 2, 5, 3, 4, 1} --array = {2,14,4,6,8,1,3,5,7,9,10,11,0,13,12,-1} --array = {"the","quick","brown","fox","jumps","over","the","lazy","dog"} --array = {0.603704, 0.293639, 0.513965, 0.746246, 0.245282, 0.930508, 0.550878, 0.622534, 0.006089, 0.270426} --array = shuffle(deep_copy(array)) circle_sort()
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#VBScript
VBScript
Function quicksort(arr,s,n) l = s r = s + n - 1 p = arr(Int((l + r)/2)) Do Until l > r Do While arr(l) < p l = l + 1 Loop Do While arr(r) > p r = r -1 Loop If l <= r Then tmp = arr(l) arr(l) = arr(r) arr(r) = tmp l = l + 1 r = r - 1 End If Loop If s < r Then Call quicksort(arr,s,r-s+1) End If If l < t Then Call quicksort(arr,l,t-l+1) End If quicksort = arr End Function   myarray=Array(9,8,7,6,5,5,4,3,2,1,0,-1) m = quicksort(myarray,0,12) WScript.Echo Join(m,",")
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
#AWK
AWK
function combsort( a, len, gap, igap, swap, swaps, i ) { gap = len swaps = 1   while( gap > 1 || swaps ) { gap /= 1.2473; if ( gap < 1 ) gap = 1 i = swaps = 0 while( i + gap < len ) { igap = i + int(gap) if ( a[i] > a[igap] ) { swap = a[i] a[i] = a[igap] a[igap] = swap swaps = 1 } i++; } } }   BEGIN { a[0] = 5 a[1] = 2 a[2] = 7 a[3] = -11 a[4] = 6 a[5] = 1   combsort( a, length(a) )   for( i=0; i<length(a); i++ ) print a[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.
#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 KnuthShuffle(INT ARRAY tab BYTE size) BYTE i,j INT tmp   i=size-1 WHILE i>0 DO j=Rand(i+1) tmp=tab(i) tab(i)=tab(j) tab(j)=tmp i==-1 OD RETURN   BYTE FUNC IsSorted(INT ARRAY tab BYTE size) BYTE i   IF size<2 THEN RETURN (1) FI FOR i=0 TO size-2 DO IF tab(i)>tab(i+1) THEN RETURN (0) FI OD RETURN (1)   PROC BogoSort(INT ARRAY a INT size) WHILE IsSorted(a,size)=0 DO KnuthShuffle(a,size) OD RETURN   PROC Test(INT ARRAY a INT size) PrintE("Array before sort:") PrintArray(a,size) BogoSort(a,size) PrintE("Array after sort:") PrintArray(a,size) PutE() RETURN   PROC Main() INT ARRAY a(10)=[1 4 65535 0 7 4 20 65530], b(21)=[3 2 1 0 65535 65534 65533], 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,8) Test(b,7) Test(c,8) Test(d,12) RETURN
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Python
Python
  #python3 #tests: expect no output. #doctest with python3 -m doctest thisfile.py #additional tests: python3 thisfile.py   def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps': ''' >>> L = [3, 2, 8, 28, 2,] >>> circle_sort(L) 3 >>> print(L) [2, 2, 3, 8, 28] >>> L = [3, 2, 8, 28,] >>> circle_sort(L) 1 >>> print(L) [2, 3, 8, 28] ''' n = R-L if n < 2: return 0 swaps = 0 m = n//2 for i in range(m): if A[R-(i+1)] < A[L+i]: (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],) swaps += 1 if (n & 1) and (A[L+m] < A[L+m-1]): (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],) swaps += 1 return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)   def circle_sort(L:list)->'sort A in place, returning the number of swaps': swaps = 0 s = 1 while s: s = circle_sort_backend(L, 0, len(L)) swaps += s return swaps   # more tests! if __name__ == '__main__': from random import shuffle for i in range(309): L = list(range(i)) M = L[:] shuffle(L) N = L[:] circle_sort(L) if L != M: print(len(L)) print(N) print(L)  
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Visual_Basic
Visual Basic
Sub QuickSort(arr() As Integer, ByVal f As Integer, ByVal l As Integer) i = f 'First j = l 'Last Key = arr(i) 'Pivot Do While i < j Do While i < j And Key < arr(j) j = j - 1 Loop If i < j Then arr(i) = arr(j): i = i + 1 Do While i < j And Key > arr(i) i = i + 1 Loop If i < j Then arr(j) = arr(i): j = j - 1 Loop arr(i) = Key If i - 1 > f Then QuickSort arr(), f, i - 1 If j + 1 < l Then QuickSort arr(), j + 1, l End Sub
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
#BBC_BASIC
BBC BASIC
DEF PROC_CombSort11(Size%)   gap%=Size% REPEAT IF gap% > 1 THEN gap%=gap% / 1.3 IF gap%=9 OR gap%=10 gap%=11 ENDIF I% = 1 Finished%=TRUE REPEAT IF data%(I%) > data%(I%+gap%) THEN SWAP data%(I%),data%(I%+gap%) Finished% = FALSE ENDIF I%+=1 UNTIL I%+gap% > Size% UNTIL gap%=1 AND Finished%   ENDPROC
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.
#ActionScript
ActionScript
public function bogoSort(arr:Array):Array { while (!sorted(arr)) { shuffle(arr); }   return arr; }   public function shuffle(arr:Array):void { for (var i:int = 0; i < arr.length; i++) { var rand:int = Math.floor(Math.random() * arr.length); var tmp:* = arr[i]; arr[i] = arr[rand]; arr[rand] = tmp; } }   public function sorted(arr:Array):Boolean { var last:int = arr[0];   for (var i:int = 1; i < arr.length; i++) { if (arr[i] < last) { return false; }   last = arr[i]; }   return true; }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Quackery
Quackery
[ dup size 2 < iff [ drop true ] done true swap dup [] != if [ behead swap witheach [ tuck > if [ dip not conclude ] ] ] drop ] is sorted ( [ --> b )   [ behead swap witheach [ 2dup < iff nip else drop ] ] is largest ( [ --> n )   [ dup largest 1+ over size dup 1 [ 2dup > while 1 << again ] nip swap - dup dip [ of join ] swap ] is pad ( [ --> n [ )   [ swap dup if [ negate split drop ] ] is unpad ( n [ --> [ )   [ dup size times [ i i^ > not iff conclude done dup i peek over i^ peek 2dup < iff [ rot i poke i^ poke ] else 2drop ] ] is reorder ( [ --> [ )   [ pad [ [ dup sorted if done reorder dup size 2 / split recurse swap recurse swap join ] dup sorted until ] unpad ] is circlesort ( [ --> [ )   $ "bababadalgharaghtakamminarronnkonnbronntonnerronntuonnthunntrovarrhounawnskawntoohoohoordenenthurnuk" dup echo$ cr circlesort echo$ cr
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Racket
Racket
#lang racket (define (circle-sort v0 [<? <]) (define v (vector-copy v0))   (define (swap-if l r) (define v.l (vector-ref v l)) (define v.r (vector-ref v r)) (and (<? v.r v.l) (begin (vector-set! v l v.r) (vector-set! v r v.l) #t)))   (define (inr-cs! L R) (cond [(>= L (- R 1)) #f] ; covers 0 or 1 vectors [else (define M (quotient (+ L R) 2)) (define I-moved? (for/or ([l (in-range L M)] [r (in-range (- R 1) L -1)]) (swap-if l r))) (define M-moved? (and (odd? (- L R)) (> M 0) (swap-if (- M 1) M))) (define L-moved? (inr-cs! L M)) (define R-moved? (inr-cs! M R)) (or I-moved? L-moved? R-moved? M-moved?)]))   (let loop () (when (inr-cs! 0 (vector-length v)) (loop))) v)   (define (sort-random-vector) (define v (build-vector (+ 2 (random 10)) (λ (i) (random 100)))) (define v< (circle-sort v <)) (define sorted? (apply <= (vector->list v<))) (printf " ~.a\n-> ~.a [~a]\n\n" v v< sorted?))   (for ([_ 10]) (sort-random-vector))   (circle-sort '#("table" "chair" "cat" "sponge") string<?)
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Vlang
Vlang
fn partition(mut arr []int, low int, high int) int { pivot := arr[high] mut i := (low - 1) for j in low .. high { if arr[j] < pivot { i++ temp := arr[i] arr[i] = arr[j] arr[j] = temp } } temp := arr[i + 1] arr[i + 1] = arr[high] arr[high] = temp return i + 1 }   fn quick_sort(mut arr []int, low int, high int) { if low < high { pi := partition(mut arr, low, high) quick_sort(mut arr, low, pi - 1) quick_sort(mut arr, pi + 1, high) } }   fn main() { mut arr := [4, 65, 2, -31, 0, 99, 2, 83, 782, 1] n := arr.len - 1 println('Input: ' + arr.str()) quick_sort(mut arr, 0, n) println('Output: ' + arr.str()) }
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
#C
C
void Combsort11(double a[], int nElements) { int i, j, gap, swapped = 1; double temp;   gap = nElements; while (gap > 1 || swapped == 1) { gap = gap * 10 / 13; if (gap == 9 || gap == 10) gap = 11; if (gap < 1) gap = 1; swapped = 0; for (i = 0, j = gap; j < nElements; i++, j++) { if (a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; swapped = 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.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Discrete_Random;   procedure Test_Bogosort is generic type Ordered is private; type List is array (Positive range <>) of Ordered; with function "<" (L, R : Ordered) return Boolean is <>; procedure Bogosort (Data : in out List);   procedure Bogosort (Data : in out List) is function Sorted return Boolean is begin for I in Data'First..Data'Last - 1 loop if not (Data (I) < Data (I + 1)) then return False; end if; end loop; return True; end Sorted; subtype Index is Integer range Data'Range; package Dices is new Ada.Numerics.Discrete_Random (Index); use Dices; Dice : Generator; procedure Shuffle is J  : Index; Temp : Ordered; begin for I in Data'Range loop J := Random (Dice); Temp := Data (I); Data (I) := Data (J); Data (J) := Temp; end loop; end Shuffle; begin while not Sorted loop Shuffle; end loop; end Bogosort;   type List is array (Positive range <>) of Integer; procedure Integer_Bogosort is new Bogosort (Integer, List); Sequence : List := (7,6,3,9); begin Integer_Bogosort (Sequence); for I in Sequence'Range loop Put (Integer'Image (Sequence (I))); end loop; end Test_Bogosort;
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Raku
Raku
sub circlesort (@x, $beg, $end) { my $swaps = 0; if $beg < $end { my ($lo, $hi) = $beg, $end; repeat { if @x[$lo] after @x[$hi] { @x[$lo,$hi] .= reverse; ++$swaps; } ++$hi if --$hi == ++$lo } while $lo < $hi; $swaps += circlesort(@x, $beg, $hi); $swaps += circlesort(@x, $lo, $end); } $swaps; }   say my @x = (-100..100).roll(20); say @x while circlesort(@x, 0, @x.end);   say @x = <The quick brown fox jumps over the lazy dog.>; say @x while circlesort(@x, 0, @x.end);
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Wart
Wart
def (qsort (pivot ... ns)) (+ (qsort+keep (fn(_) (_ < pivot)) ns) list.pivot (qsort+keep (fn(_) (_ > pivot)) ns))   def (qsort x) :case x=nil nil
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
#C.23
C#
using System;   namespace CombSort { class Program { static void Main(string[] args) { int[] unsorted = new int[] { 3, 5, 1, 9, 7, 6, 8, 2, 4 }; Console.WriteLine(string.Join(",", combSort(unsorted))); } public static int[] combSort(int[] input) { double gap = input.Length; bool swaps = true; while (gap > 1 || swaps) { gap /= 1.247330950103979; if (gap < 1) { gap = 1; } int i = 0; swaps = false; while (i + gap < input.Length) { int igap = i + (int)gap; if (input[i] > input[igap]) { int swap = input[i]; input[i] = input[igap]; input[igap] = swap; swaps = true; } i++; } } return input; } } }
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.
#ALGOL_68
ALGOL 68
MODE TYPE = INT;   PROC random shuffle = (REF[]TYPE l)VOID: ( INT range = UPB l - LWB l + 1; FOR index FROM LWB l TO UPB l DO TYPE tmp := l[index]; INT other := ENTIER (LWB l + random * range); l[index] := l[other]; l[other] := tmp OD );   PROC in order = (REF[]TYPE l)BOOL: ( IF LWB l >= UPB l THEN TRUE ELSE TYPE last := l[LWB l]; FOR index FROM LWB l + 1 TO UPB l DO IF l[index] < last THEN GO TO return false FI; last := l[index] OD; TRUE EXIT return false: FALSE FI );   PROC bogo sort = (REF[]TYPE l)REF[]TYPE: ( WHILE NOT in order(l) DO random shuffle(l) OD; l );   [6]TYPE sample := (61, 52, 63, 94, 46, 18); print((bogo sort(sample), new line))
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#REXX
REXX
/*REXX program uses a circle sort algorithm to sort an array (or list) of numbers. */ parse arg x /*obtain optional arguments from the CL*/ if x='' | x="," then x= 6 7 8 9 2 5 3 4 1 /*Not specified? Then use the default.*/ call make_array 'before sort:' /*display the list and make an array. */ call circleSort # /*invoke the circle sort subroutine. */ call make_list ' after sort:' /*make a list and display it to console*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ circleSort: do while .circleSrt(1, arg(1), 0)\==0; end; return make_array: #= words(x); do i=1 for #; @.i= word(x, i); end; say arg(1) x; return make_list: y= @.1; do j=2 for #-1; y= y @.j; end; say arg(1) y; return .swap: parse arg a,b; parse value @.a @.b with @.b @.a; swaps= swaps+1; return /*──────────────────────────────────────────────────────────────────────────────────────*/ .circleSrt: procedure expose @.; parse arg LO,HI,swaps /*obtain LO & HI arguments.*/ if LO==HI then return swaps /*1 element? Done with sort.*/ high= HI; low= LO; mid= (HI-LO) % 2 /*assign some indices. */ /* [↓] sort a section of #'s*/ do while LO<HI /*sort within a section. */ if @.LO>@.HI then call .swap LO,HI /*are numbers out of order ? */ LO= LO + 1; HI= HI - 1 /*add to LO; shrink the HI. */ end /*while*/ /*just process one section. */ _= HI + 1 /*point to HI plus one. */ if LO==HI & @.LO>@._ then call .swap LO, _ /*numbers still out of order?*/ swaps= .circleSrt(low, low+mid, swaps) /*sort the lower section. */ swaps= .circleSrt(low+mid+1, high, swaps) /* " " higher " */ return swaps /*the section sorting is done*/
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Wren
Wren
import "/sort" for Sort   var as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3], ["echo", "lima", "charlie", "whiskey", "golf", "papa", "alfa", "india", "foxtrot", "kilo"] ] for (a in as) { System.print("Before: %(a)") Sort.quick(a) System.print("After : %(a)") System.print() }
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
#C.2B.2B
C++
template<class ForwardIterator> void combsort ( ForwardIterator first, ForwardIterator last ) { static const double shrink_factor = 1.247330950103979; typedef typename std::iterator_traits<ForwardIterator>::difference_type difference_type; difference_type gap = std::distance(first, last); bool swaps = true;   while ( (gap > 1) || (swaps == true) ){ if (gap > 1) gap = static_cast<difference_type>(gap/shrink_factor);   swaps = false; ForwardIterator itLeft(first); ForwardIterator itRight(first); std::advance(itRight, gap);   for ( ; itRight!=last; ++itLeft, ++itRight ){ if ( (*itRight) < (*itLeft) ){ std::iter_swap(itLeft, itRight); swaps = true; } } } }
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.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program bogosort.s */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .ascii "Value  : " sMessValeur: .fill 11, 1, ' ' @ size => 11 szCarriageReturn: .asciz "\n"   .align 4 iGraine: .int 123456 .equ NBELEMENTS, 6 TableNumber: .int 1,2,3,4,5,6,7,8,9,10   /*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   1: ldr r0,iAdrTableNumber @ address number table mov r1,#NBELEMENTS @ number of élements bl knuthShuffle   @ table display elements ldr r2,iAdrTableNumber mov r3,#0 2: @ loop display table ldr r0,[r2,r3,lsl #2] ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function ldr r0,iAdrsMessResult bl affichageMess @ display message add r3,#1 cmp r3,#NBELEMENTS - 1 ble 2b ldr r0,iAdrszCarriageReturn bl affichageMess   ldr r0,iAdrTableNumber @ address number table mov r1,#NBELEMENTS @ number of élements bl isSorted @ control sort cmp r0,#1 @ sorted ? bne 1b @ no -> loop     100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrsMessValeur: .int sMessValeur iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResult: .int sMessResult iAdrTableNumber: .int TableNumber /******************************************************************/ /* control sorted table */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the number of elements > 0 */ /* r0 return 0 if not sorted 1 if sorted */ isSorted: push {r2-r4,lr} @ save registers mov r2,#0 ldr r4,[r0,r2,lsl #2] 1: add r2,#1 cmp r2,r1 movge r0,#1 bge 100f ldr r3,[r0,r2, lsl #2] cmp r3,r4 movlt r0,#0 blt 100f mov r4,r3 b 1b 100: pop {r2-r4,lr} bx lr @ return /******************************************************************/ /* knuthShuffle Shuffle */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the number of elements */ knuthShuffle: push {r2-r5,lr} @ save registers mov r5,r0 @ save table address mov r2,#0 @ start index 1: mov r0,r2 @ generate aleas bl genereraleas ldr r3,[r5,r2,lsl #2] @ swap number on the table ldr r4,[r5,r0,lsl #2] str r4,[r5,r2,lsl #2] str r3,[r5,r0,lsl #2] add r2,#1 @ next number cmp r2,r1 @ end ? blt 1b @ no -> loop   100: pop {r2-r5,lr} bx lr @ return   /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ bx lr @ return /******************************************************************/ /* Converting a register to a decimal unsigned */ /******************************************************************/ /* r0 contains value and r1 address area */ /* r0 return size of result (no zero final in area) */ /* area size => 11 bytes */ .equ LGZONECAL, 10 conversion10: push {r1-r4,lr} @ save registers mov r3,r1 mov r2,#LGZONECAL   1: @ start loop bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area cmp r0,#0 @ stop if quotient = 0 subne r2,#1 @ else previous position bne 1b @ and loop @ and move digit from left of area mov r4,#0 2: ldrb r1,[r3,r2] strb r1,[r3,r4] add r2,#1 add r4,#1 cmp r2,#LGZONECAL ble 2b @ and move spaces in end on area mov r0,r4 @ result length mov r1,#' ' @ space 3: strb r1,[r3,r4] @ store space in area add r4,#1 @ next position cmp r4,#LGZONECAL ble 3b @ loop if r4 <= area size   100: pop {r1-r4,lr} @ restaur registres bx lr @return   /***************************************************/ /* division par 10 unsigned */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10U: push {r2,r3,r4, lr} mov r4,r0 @ save value //mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3 //movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3 ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2 umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3 add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2,r3,r4,lr} bx lr @ leave function iMagicNumber: .int 0xCCCCCCCD /***************************************************/ /* Generation random number */ /***************************************************/ /* r0 contains limit */ genereraleas: push {r1-r4,lr} @ save registers ldr r4,iAdriGraine ldr r2,[r4] ldr r3,iNbDep1 mul r2,r3,r2 ldr r3,iNbDep1 add r2,r2,r3 str r2,[r4] @ maj de la graine pour l appel suivant cmp r0,#0 beq 100f mov r1,r0 @ divisor mov r0,r2 @ dividende bl division mov r0,r3 @ résult = remainder   100: @ end function pop {r1-r4,lr} @ restaur registers bx lr @ return /*****************************************************/ iAdriGraine: .int iGraine iNbDep1: .int 0x343FD iNbDep2: .int 0x269EC3 /***************************************************/ /* integer division unsigned */ /***************************************************/ division: /* r0 contains dividend */ /* r1 contains divisor */ /* r2 returns quotient */ /* r3 returns remainder */ push {r4, lr} mov r2, #0 @ init quotient mov r3, #0 @ init remainder mov r4, #32 @ init counter bits b 2f 1: @ loop movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1) adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C cmp r3, r1 @ compute r3 - r1 and update cpsr subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1 adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C 2: subs r4, r4, #1 @ r4 <- r4 - 1 bpl 1b @ if r4 >= 0 (N=0) then loop pop {r4, lr} bx lr    
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Ring
Ring
  # Project : Sorting Algorithms/Circle Sort   test = [-4, -1, 1, 0, 5, -7, -2, 4, -6, -3, 2, 6, 3, 7, -5] while circlesort(1, len(test), 0) end showarray(test)   func circlesort(lo, hi, swaps) if lo = hi return swaps ok high = hi low = lo mid = floor((hi-lo)/2) while lo < hi if test[lo] > test[hi] temp = test[lo] test[lo] = test[hi] test[hi] = temp swaps = swaps + 1 ok lo = lo + 1 hi = hi - 1 end if lo = hi if test[lo] > test[hi+1] temp = test[lo] test[lo] = test[hi+1] test[hi + 1] = temp swaps = swaps + 1 ok ok swaps = circlesort(low, low+mid, swaps) swaps = circlesort(low+mid+1 ,high, swaps) return swaps   func showarray(vect) see "[" svect = "" for n = 1 to len(vect) svect = svect + vect[n] + ", " next svect = left(svect, len(svect) - 2) see svect see "]" + nl  
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Ruby
Ruby
class Array def circle_sort! while _circle_sort!(0, size-1) > 0 end self end   private def _circle_sort!(lo, hi, swaps=0) return swaps if lo == hi low, high = lo, hi mid = (lo + hi) / 2 while lo < hi if self[lo] > self[hi] self[lo], self[hi] = self[hi], self[lo] swaps += 1 end lo += 1 hi -= 1 end if lo == hi && self[lo] > self[hi+1] self[lo], self[hi+1] = self[hi+1], self[lo] swaps += 1 end swaps + _circle_sort!(low, mid) + _circle_sort!(mid+1, high) end end   ary = [6, 7, 8, 9, 2, 5, 3, 4, 1] puts "before sort: #{ary}" puts " after sort: #{ary.circle_sort!}"
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations string 0; \use zero-terminated strings   proc QSort(Array, Num); \Quicksort Array into ascending order char Array; \address of array to sort int Num; \number of elements in the array int I, J, Mid, Temp; [I:= 0; J:= Num-1; Mid:= Array(J>>1); while I <= J do [while Array(I) < Mid do I:= I+1; while Array(J) > Mid do J:= J-1; if I <= J then [Temp:= Array(I); Array(I):= Array(J); Array(J):= Temp; I:= I+1; J:= J-1; ]; ]; if I < Num-1 then QSort(@Array(I), Num-I); if J > 0 then QSort(Array, J+1); ]; \QSort   func StrLen(Str); \Return number of characters in an ASCIIZ string char Str; int I; for I:= 0 to -1>>1-1 do if Str(I) = 0 then return I;   char Str; [Str:= "Pack my box with five dozen liquor jugs."; QSort(Str, StrLen(Str), 1); Text(0, Str); CrLf(0); ]
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.
#11l
11l
F gnomesort(&a) V i = 1 V j = 2 L i < a.len I a[i - 1] <= a[i] i = j j++ E swap(&a[i - 1], &a[i]) i-- I i == 0 i = j j++ R a   print(gnomesort(&[3, 4, 2, 5, 1, 6]))
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
#COBOL
COBOL
C-PROCESS SECTION. C-000. DISPLAY "SORT STARTING".   MOVE WC-SIZE TO WC-GAP.   PERFORM E-COMB UNTIL WC-GAP = 1 AND FINISHED.   DISPLAY "SORT FINISHED".   C-999. EXIT.   E-COMB SECTION. E-000. IF WC-GAP > 1 DIVIDE WC-GAP BY 1.3 GIVING WC-GAP IF WC-GAP = 9 OR 10 MOVE 11 TO WC-GAP.   MOVE 1 TO WC-SUB-1. MOVE "Y" TO WF-FINISHED.   PERFORM F-SCAN UNTIL WC-SUB-1 + WC-GAP > WC-SIZE.   E-999. EXIT.   F-SCAN SECTION. F-000. ADD WC-SUB-1 WC-GAP GIVING WC-SUB-2. IF WB-ENTRY(WC-SUB-1) > WB-ENTRY(WC-SUB-2) MOVE WB-ENTRY(WC-SUB-1) TO WC-TEMP MOVE WB-ENTRY(WC-SUB-2) TO WB-ENTRY(WC-SUB-1) MOVE WC-TEMP TO WB-ENTRY(WC-SUB-2) MOVE "N" TO WF-FINISHED.   ADD 1 TO WC-SUB-1.   F-999. EXIT.
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.
#Arturo
Arturo
bogoSort: function [items][ a: new items while [not? sorted? a]-> shuffle 'a return a ]   print bogoSort [3 1 2 8 5 7 9 4 6]
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Rust
Rust
fn _circle_sort<T: PartialOrd>(a: &mut [T], low: usize, high: usize, swaps: usize) -> usize { if low == high { return swaps; } let mut lo = low; let mut hi = high; let mid = (hi - lo) / 2; let mut s = swaps; while lo < hi { if a[lo] > a[hi] { a.swap(lo, hi); s += 1; } lo += 1; hi -= 1; } if lo == hi { if a[lo] > a[hi + 1] { a.swap(lo, hi + 1); s += 1; } } s = _circle_sort(a, low, low + mid, s); s = _circle_sort(a, low + mid + 1, high, s); return s; }   fn circle_sort<T: PartialOrd>(a: &mut [T]) { let len = a.len(); loop { if _circle_sort(a, 0, len - 1, 0) == 0 { break; } } }   fn main() { let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6]; println!("before: {:?}", v); circle_sort(&mut v); println!("after: {:?}", v); }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Scala
Scala
object CircleSort extends App {   def sort(arr: Array[Int]): Array[Int] = { def circleSortR(arr: Array[Int], _lo: Int, _hi: Int, _numSwaps: Int): Int = { var lo = _lo var hi = _hi var numSwaps = _numSwaps   def swap(arr: Array[Int], idx1: Int, idx2: Int): Unit = { val tmp = arr(idx1) arr(idx1) = arr(idx2) arr(idx2) = tmp }   if (lo == hi) return numSwaps val (high, low) = (hi, lo) val mid = (hi - lo) / 2 while ( lo < hi) { if (arr(lo) > arr(hi)) { swap(arr, lo, hi) numSwaps += 1 } lo += 1 hi -= 1 } if (lo == hi && arr(lo) > arr(hi + 1)) { swap(arr, lo, hi + 1) numSwaps += 1 }   circleSortR(arr, low + mid + 1, high, circleSortR(arr, low, low + mid, numSwaps)) }   while (circleSortR(arr, 0, arr.length - 1, 0) != 0)() arr }   println(sort(Array[Int](2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1)).mkString(", "))   }
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Z80_Assembly
Z80 Assembly
;-------------------------------------------------------------------------------------------------------------------- ; Quicksort, inputs (__sdcccall(1) calling convention): ; HL = uint16_t* A (pointer to beginning of array) ; DE = uint16_t len (number of word elements in array) ; modifies: AF, A'F', BC, DE, HL ; WARNING: array can't be aligned to start/end of 64ki address space, like HL == 0x0000, or having last value at 0xFFFE ; WARNING: stack space required is on average about 6*log(len) (depending on the data, in extreme case it may be more) quicksort_a: ; convert arguments to HL=A.begin(), DE=A.end() and continue with quicksort_a_impl ex de,hl add hl,hl add hl,de ex de,hl ; | ; fallthrough into implementation ; | ; v ;-------------------------------------------------------------------------------------------------------------------- ; Quicksort implementation, inputs: ; HL = uint16_t* A.begin() (pointer to beginning of array) ; DE = uint16_t* A.end() (pointer beyond array) ; modifies: AF, A'F', BC, HL (DE is preserved) quicksort_a_impl: ; array must be located within 0x0002..0xFFFD ld c,l ld b,h ; BC = A.begin() ; if (len < 2) return; -> if (end <= begin+2) return; inc hl inc hl or a sbc hl,de ; HL = -(2*len-2), len = (2-HL)/2 ret nc ; case: begin+2 >= end <=> (len < 2)   push de ; preserve A.end() for recursion push bc ; preserve A.begin() for recursion   ; uint16_t pivot = A[len / 2]; rr h rr l dec hl res 0,l add hl,de ld a,(hl) inc hl ld l,(hl) ld h,b ld b,l ld l,c ld c,a ; HL = A.begin(), DE = A.end(), BC = pivot   ; flip HL/DE meaning, it makes simpler the recursive tail and (A[j] > pivot) test ex de,hl ; DE = A.begin(), HL = A.end(), BC = pivot dec de ; but keep "from" address (related to A[i]) at -1 as "default" state   ; for (i = 0, j = len - 1; ; i++, j--) { ; DE = (A+i-1).hi, HL = A+j+1 .find_next_swap:   ; while (A[j] > pivot) j--; .find_j: dec hl ld a,b sub (hl) dec hl ; HL = A+j (finally) jr c,.find_j ; if cf=1, A[j].hi > pivot.hi jr nz,.j_found ; if zf=0, A[j].hi < pivot.hi ld a,c ; if (A[j].hi == pivot.hi) then A[j].lo vs pivot.lo is checked sub (hl) jr c,.find_j .j_found:   ; while (A[i] < pivot) i++; .find_i: inc de ld a,(de) inc de ; DE = (A+i).hi (ahead +0.5 for swap) sub c ld a,(de) sbc a,b jr c,.find_i ; cf=1 -> A[i] < pivot   ; if (i >= j) break; // DE = (A+i).hi, HL = A+j, BC=pivot sbc hl,de ; cf=0 since `jr c,.find_i` jr c,.swaps_done add hl,de ; DE = (A+i).hi, HL = A+j   ; swap(A[i], A[j]); inc hl ld a,(de) ldd ex af,af ld a,(de) ldi ex af,af ld (hl),a ; Swap(A[i].hi, A[j].hi) done dec hl ex af,af ld (hl),a ; Swap(A[i].lo, A[j].lo) done   inc bc inc bc ; pivot value restored (was -=2 by ldd+ldi) ; --j; HL = A+j is A+j+1 for next loop (ready) ; ++i; DE = (A+i).hi is (A+i-1).hi for next loop (ready) jp .find_next_swap   .swaps_done: ; i >= j, all elements were already swapped WRT pivot, call recursively for the two sub-parts dec de ; DE = A+i   ; quicksort_c(A, i); pop hl ; HL = A call quicksort_a_impl   ; quicksort_c(A + i, len - i); ex de,hl ; HL = A+i pop de ; DE = end() (and return it preserved) jp quicksort_a_impl
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.
#360_Assembly
360 Assembly
* Gnome sort - Array base 0 - 15/04/2020 GNOME CSECT USING GNOME,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability LA R6,1 i=1 LA R7,2 j=2 DO WHILE=(C,R6,LT,NN) while i<nn LR R1,R6 i SLA R1,2 ~ LA R8,TT-4(R1) @tt(i-1) LA R9,TT(R1) @tt(i) L R2,0(R8) tt(i-1) IF C,R2,LE,0(R9) THEN if tt(i-1)<=tt(i) then LR R6,R7 i=j LA R7,1(R7) j=j+1 ELSE , else L R4,0(R8) t=tt(i-1) L R3,0(R9) tt(i) ST R3,0(R8) tt(i-1)=tt(i) ST R4,0(R9) tt(i)=t BCTR R6,0 i=i-1 IF LTR,R6,Z,R6 THEN if i=0 then LR R6,R7 i=j LA R7,1(R7) j=j+1 ENDIF , endif ENDIF , endif ENDDO , endwhile LA R10,PG @buffer LA R7,TT @tt LA R6,1 i=1 DO WHILE=(C,R6,LE,NN) do i=1 to nn L R2,0(R7) tt(i) XDECO R2,XDEC edit tt(i) MVC 0(5,R10),XDEC+7 output tt(i) LA R10,5(R10) @buffer LA R7,4(R7) @tt++ LA R6,1(R6) i++ ENDDO , enddo i XPRNT PG,L'PG print buffer L R13,4(0,R13) restore previous savearea pointer RETURN (14,12),RC=0 restore registers from calling save TT DC F'557',F'5143',F'5432',F'6798',F'2874' DC F'3499',F'6949',F'4992',F'2555',F'4175' DC F'8264',F'3522',F'2045',F'2963',F'2625' DC F'-764',F'1845',F'1485',F'5792',F'7562' DC F'5044',F'3598',F'6817',F'4891',F'4350' NN DC A((NN-TT)/L'TT) number of items of tt XDEC DS CL12 temp for xdeco PG DC CL125' ' buffer REGEQU END GNOME
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.)
#11l
11l
F countingSort(a, min, max) V cnt = [0] * (max - min + 1) L(x) a cnt[x - min]++   [Int] result L(n) cnt result [+]= [L.index + min] * n R result   V data = [9, 7, 10, 2, 9, 7, 4, 3, 10, 2, 7, 10, 2, 1, 3, 8, 7, 3, 9, 5, 8, 5, 1, 6, 3, 7, 5, 4, 6, 9, 9, 6, 6, 10, 2, 4, 5, 2, 8, 2, 2, 5, 2, 9, 3, 3, 5, 7, 8, 4] print(countingSort(data, min(data), max(data)) == sorted(data))
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
#Common_Lisp
Common Lisp
(defparameter *shrink* 1.3)   (defun comb-sort (input) (loop with input-size = (length input) with gap = input-size with swapped do (when (> gap 1) (setf gap (floor gap *shrink*))) (setf swapped nil) (loop for lo from 0 for hi from gap below input-size when (> (aref input lo) (aref input hi)) do (rotatef (aref input lo) (aref input hi)) (setf swapped t)) while (or (> gap 1) swapped) finally (return input)))
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.
#AutoHotkey
AutoHotkey
MsgBox % Bogosort("987654") MsgBox % Bogosort("319208") MsgBox % Bogosort("fedcba") MsgBox % Bogosort("gikhjl")   Bogosort(sequence) { While !Sorted(sequence) sequence := Shuffle(sequence) Return sequence }   Sorted(sequence) { Loop, Parse, sequence { current := A_LoopField rest := SubStr(sequence, A_Index) Loop, Parse, rest { If (current > A_LoopField) Return false } } Return true }   Shuffle(sequence) { Max := StrLen(sequence) + 1 Loop % StrLen(sequence) { Random, Num, 1, % Max - A_Index Found .= SubStr(sequence, Num, 1) sequence := SubStr(sequence, 1, Num-1) . SubStr(sequence, Num+1) } Return Found }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Sidef
Sidef
func circlesort(arr, beg=0, end=arr.end) { var swaps = 0 if (beg < end) { var (lo, hi) = (beg, end) do { if (arr[lo] > arr[hi]) { arr.swap(lo, hi) ++swaps } ++hi if (--hi == ++lo) } while (lo < hi) swaps += circlesort(arr, beg, hi) swaps += circlesort(arr, lo, end) } return swaps }   var numbers = %n(2 3 3 5 5 1 1 7 7 6 6 4 4 0 0) do { say numbers } while circlesort(numbers)   var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane", "Alice"] do { say strs } while circlesort(strs)
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#zkl
zkl
fcn qtSort(list,cmp=Op("<")){ // sort immutable lists fcn(list,cmp,N){ // spendy to keep recreating cmp reg pivot=list[0], rest=list[1,*]; left,right:=rest.filter22(cmp,pivot); N+=1; T.extend(self.fcn(left,cmp,N),T(pivot),self.fcn(right,cmp,N)); }(list,cmp,0); }
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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program gnomeSort64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeConstantesARM64.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data szMessSortOk: .asciz "Table sorted.\n" szMessSortNok: .asciz "Table not sorted !!!!!.\n" sMessResult: .asciz "Value  : @ \n" szCarriageReturn: .asciz "\n"   .align 4 TableNumber: .quad 1,3,6,2,5,9,10,8,4,7 #TableNumber: .quad 10,9,8,7,6,-5,4,3,2,1 .equ NBELEMENTS, (. - TableNumber) / 8 /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x0,qAdrTableNumber // address number table mov x1,0 // first element mov x2,NBELEMENTS // number of élements bl gnomeSort ldr x0,qAdrTableNumber // address number table bl displayTable   ldr x0,qAdrTableNumber // address number table mov x1,NBELEMENTS // number of élements bl isSorted // control sort cmp x0,1 // sorted ? beq 1f ldr x0,qAdrszMessSortNok // no !! error sort bl affichageMess b 100f 1: // yes ldr x0,qAdrszMessSortOk bl affichageMess 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 qAdrTableNumber: .quad TableNumber qAdrszMessSortOk: .quad szMessSortOk qAdrszMessSortNok: .quad szMessSortNok /******************************************************************/ /* control sorted table */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the number of elements > 0 */ /* x0 return 0 if not sorted 1 if sorted */ isSorted: stp x2,lr,[sp,-16]! // save registers stp x3,x4,[sp,-16]! // save registers mov x2,0 ldr x4,[x0,x2,lsl 3] 1: add x2,x2,1 cmp x2,x1 bge 99f ldr x3,[x0,x2, lsl 3] cmp x3,x4 blt 98f mov x4,x3 b 1b 98: mov x0,0 // not sorted b 100f 99: mov x0,1 // sorted 100: ldp x3,x4,[sp],16 // restaur 2 registers ldp x2,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* gnome sort */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the first element */ /* x2 contains the number of element */ gnomeSort: 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 sub x2,x2,1 // compute end index n - 1 add x3,x1,1 // index i add x7,x1,2 // index j 1: // start loop 1 cmp x3,x2 bgt 100f sub x4,x3,1 // ldr x5,[x0,x3,lsl 3] // load value A[j] ldr x6,[x0,x4,lsl 3] // load value A[j+1] cmp x5,x6 // compare value bge 2f str x6,[x0,x3,lsl 3] // if smaller inversion str x5,[x0,x4,lsl 3] sub x3,x3,1 // i = i - 1 cmp x3,x1 bne 1b // loop 1 2: mov x3,x7 // i = j add x7,x7,1 // j = j + 1 b 1b // loop 1   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 mov x2,x0 // table address mov x3,0 1: // loop display table ldr x0,[x2,x3,lsl 3] ldr x1,qAdrsZoneConv bl conversion10S // décimal conversion ldr x0,qAdrsMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message add x3,x3,1 cmp x3,NBELEMENTS - 1 ble 1b ldr x0,qAdrszCarriageReturn bl affichageMess mov x0,x2 100: 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/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.)
#360_Assembly
360 Assembly
* Counting sort - 18/04/2020 COUNTS CSECT USING COUNTS,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability LA R6,A i=1 DO WHILE=(C,R6,LE,=A(N)) do i=1 to hbound(a) L R8,0(R6) a(i) S R8,MIN k=a(i)-min LR R1,R8 k SLA R1,2 ~ L R3,COUNT(R1) count(k+1) LA R3,1(R3) +1 ST R3,COUNT(R1) count(k+1)+=1 LA R6,4(R6) i++ ENDDO , enddo i LA R7,A j=1 L R6,MIN i=min DO WHILE=(C,R6,LE,MAX) do i=min to max LR R8,R6 i S R8,MIN k=i-min WHILEC LR R1,R8 while k SLA R1,2 ..... ~ L R2,COUNT(R1) ..... count(k+1) LTR R2,R2 ..... test BNP WHENDC ..... count(k+1)>0 ST R6,0(R7) a(j)=i LA R7,4(R7) j++ LR R1,R8 k SLA R1,2 ~ L R3,COUNT(R1) count(k+1) BCTR R3,0 -1 ST R3,COUNT(R1) count(k+1)-=1 B WHILEC end while WHENDC AH R6,=H'1' i++ ENDDO , enddo i LA R9,PG @buffer LA R6,A i=1 DO WHILE=(C,R6,LE,=A(N)) do i=1 to hbound(a) L R2,0(R6) a(i) XDECO R2,XDEC edit a(i) MVC 0(3,R9),XDEC+9 output a(i) LA R9,3(R9) @buffer++ LA R6,4(R6) i++ ENDDO , enddo i XPRNT PG,L'PG print buffer L R13,4(0,R13) restore previous savearea pointer RETURN (14,12),RC=0 restore registers from calling save MIN DC F'-9' min MAX DC F'99' max A DC F'98',F'35',F'15',F'46',F'6',F'64',F'92',F'44' DC F'53',F'21',F'56',F'74',F'13',F'11',F'92',F'70' DC F'43',F'2',F'-7',F'89',F'22',F'82',F'41',F'91' DC F'28',F'51',F'0',F'39',F'29',F'34',F'15',F'26' N DC A((N-A)/L'A) hbound(a) PG DC CL96' ' buffer XDEC DS CL12 temp fo xdeco COUNT DC 200F'0' count REGEQU END COUNTS
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
#D
D
import std.stdio, std.algorithm;   void combSort(T)(T[] input) pure nothrow @safe @nogc { int gap = input.length; bool swaps = true;   while (gap > 1 || swaps) { gap = max(1, cast(int)(gap / 1.2473)); swaps = false; foreach (immutable i; 0 .. input.length - gap) if (input[i] > input[i + gap]) { input[i].swap(input[i + gap]); swaps = true; } } }   void main() { auto data = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; data.combSort; data.writeln; }
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.
#AWK
AWK
function randint(n) { return int(n * rand()) }   function sorted(sa, sn) { for(si=1; si < sn; si++) { if ( sa[si] > sa[si+1] ) return 0; } return 1 }   { line[NR] = $0 } END { # sort it with bogo sort while ( sorted(line, NR) == 0 ) { for(i=1; i <= NR; i++) { r = randint(NR) + 1 t = line[i] line[i] = line[r] line[r] = t } } #print it for(i=1; i <= NR; i++) { print line[i] } }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Swift
Swift
func circleSort<T: Comparable>(_ array: inout [T]) { func circSort(low: Int, high: Int, swaps: Int) -> Int { if low == high { return swaps } var lo = low var hi = high let mid = (hi - lo) / 2 var s = swaps while lo < hi { if array[lo] > array[hi] { array.swapAt(lo, hi) s += 1 } lo += 1 hi -= 1 } if lo == hi { if array[lo] > array[hi + 1] { array.swapAt(lo, hi + 1) s += 1 } } s = circSort(low: low, high: low + mid, swaps: s) s = circSort(low: low + mid + 1, high: high, swaps: s) return s } while circSort(low: 0, high: array.count - 1, swaps: 0) != 0 {} }   var array = [10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6] print("before: \(array)") circleSort(&array) print(" after: \(array)")   var array2 = ["one", "two", "three", "four", "five", "six", "seven", "eight"] print("before: \(array2)") circleSort(&array2) print(" after: \(array2)")
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.
#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 GnomeSort(INT ARRAY a INT size) INT i,j,tmp   i=1 j=2 WHILE i<size DO IF a(i-1)<=a(i) THEN i=j j==+1 ELSE tmp=a(i-1) a(i-1)=a(i) a(i)=tmp i==-1 IF i=0 THEN i=j j==+1 FI FI OD RETURN   PROC Test(INT ARRAY a INT size) PrintE("Array before sort:") PrintArray(a,size) GnomeSort(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/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.)
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program countSort64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeConstantesARM64.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data szMessSortOk: .asciz "Table sorted.\n" szMessSortNok: .asciz "Table not sorted !!!!!.\n" sMessResult: .asciz "Value  : @ \n" szCarriageReturn: .asciz "\n"   .align 4 #Caution : number strictly positive and not too big TableNumber: .quad 1,3,6,2,5,9,10,8,4,5 //TableNumber: .quad 10,9,8,7,6,5,4,3,2,1 .equ NBELEMENTS, (. - TableNumber) / 8 /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x0,qAdrTableNumber // address number table mov x1,NBELEMENTS // number of élements bl searchMinMax mov x3,NBELEMENTS bl countSort ldr x0,qAdrTableNumber // address number table bl displayTable   ldr x0,qAdrTableNumber // address number table mov x1,NBELEMENTS // number of élements bl isSorted // control sort cmp x0,1 // sorted ? beq 1f ldr x0,qAdrszMessSortNok // no !! error sort bl affichageMess b 100f 1: // yes ldr x0,qAdrszMessSortOk bl affichageMess 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 qAdrTableNumber: .quad TableNumber qAdrszMessSortOk: .quad szMessSortOk qAdrszMessSortNok: .quad szMessSortNok /******************************************************************/ /* control sorted table */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the number of elements > 0 */ /* x0 return table address r1 return min r2 return max */ searchMinMax: stp x3,lr,[sp,-16]! // save registers stp x3,x4,[sp,-16]! // save registers mov x3,x1 // save size mov x1,1<<62 // min mov x2,0 // max mov x4,0 // index 1: ldr x5,[x0,x4,lsl 3] cmp x5,x1 csel x1,x5,x1,lt cmp x5,x2 csel x2,x5,x2,gt add x4,x4,1 cmp x4,x3 blt 1b 100: ldp x4,x5,[sp],16 // restaur 2 registers ldp x3,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* control sorted table */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the number of elements > 0 */ /* x0 return 0 if not sorted 1 if sorted */ isSorted: stp x2,lr,[sp,-16]! // save registers stp x3,x4,[sp,-16]! // save registers mov x2,0 ldr x4,[x0,x2,lsl 3] 1: add x2,x2,1 cmp x2,x1 bge 99f ldr x3,[x0,x2, lsl 3] cmp x3,x4 blt 98f mov x4,x3 b 1b 98: mov x0,0 // not sorted b 100f 99: mov x0,1 // sorted 100: ldp x3,x4,[sp],16 // restaur 2 registers ldp x2,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* count sort */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the minimum */ /* x2 contains the maximum */ /* x3 contains area size */ /* caution : the count area is in the stack. if max is very large, risk of error */ countSort: 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 sub x3,x3,1 // compute endidx = n - 1 sub x5,x2,x1 // compute max - min add x5,x5,1 // + 1 lsl x9,x5,3 // 8 bytes by number sub sp,sp,x9 // reserve count area in stack mov fp,sp // frame pointer = stack mov x6,0 mov x4,0 1: // loop init stack area str x6,[fp,x4, lsl 3] add x4,x4,#1 cmp x4,x5 blt 1b mov x4,#0 // indice 2: // start loop 2 ldr x5,[x0,x4,lsl 3] // load value A[j] sub x5,x5,x1 // - min ldr x6,[fp,x5,lsl 3] // load count of value add x6,x6,1 // increment counter str x6,[fp,x5,lsl 3] // and store add x4,x4,1 // increment indice cmp x4,x3 // end ? ble 2b // no -> loop 2   mov x7,0 // z mov x4,x1 // index = min 3: // start loop 3 sub x6,x4,x1 // compute index - min ldr x5,[fp,x6,lsl 3] // load count 4: // start loop 4 cmp x5,0 // count <> zéro beq 5f str x4,[x0,x7,lsl 3] // store value A[j] add x7,x7,1 // increment z sub x5,x5,1 // decrement count b 4b   5: add x4,x4,1 // increment index cmp x4,x2 // max ? ble 3b // no -> loop 3   add sp,sp,x9 // stack alignement   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 mov x2,x0 // table address mov x3,0 1: // loop display table ldr x0,[x2,x3,lsl 3] ldr x1,qAdrsZoneConv bl conversion10S // décimal conversion ldr x0,qAdrsMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message add x3,x3,1 cmp x3,NBELEMENTS - 1 ble 1b ldr x0,qAdrszCarriageReturn bl affichageMess mov x0,x2 // table address 100: 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/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.)
#Action.21
Action!
DEFINE MAXSIZE="100"   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 CountingSort(INT ARRAY a INT size,min,max) INT ARRAY count(MAXSIZE) INT n,i,num,z   n=max-min+1 FOR i=0 TO n-1 DO count(i)=0 OD   FOR i=0 TO size-1 DO num=a(i) count(num-min)==+1 OD   z=0 FOR i=min TO max DO WHILE count(i-min)>0 DO a(z)=i z==+1 count(i-min)==-1 OD OD RETURN   PROC Test(INT ARRAY a INT size,min,max) PrintE("Array before sort:") PrintArray(a,size) CountingSort(a,size,min,max) 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,-6,20) Test(b,21,-10,10) Test(c,8,101,108) Test(d,12,-1,1) 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
#Delphi
Delphi
  program Comb_sort;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Types;   type THelperIntegerDynArray = record helper for TIntegerDynArray public procedure CombSort; procedure FillRange(Count: integer); procedure Shuffle; function ToString: string; end;   { THelperIntegerDynArray } procedure THelperIntegerDynArray.CombSort; var i, gap, temp: integer; swapped: boolean; begin gap := length(self); swapped := true; while (gap > 1) or swapped do begin gap := trunc(gap / 1.3); if (gap < 1) then gap := 1; swapped := false; for i := 0 to length(self) - gap - 1 do if self[i] > self[i + gap] then begin temp := self[i]; self[i] := self[i + gap]; self[i + gap] := temp; swapped := true; end; end; end;   procedure THelperIntegerDynArray.FillRange(Count: integer); var i: Integer; begin SetLength(self, Count); for i := 0 to Count - 1 do Self[i] := i; end;   procedure THelperIntegerDynArray.Shuffle; var i, j, tmp: integer; count: integer; begin Randomize; count := Length(self); for i := 0 to count - 1 do begin j := i + Random(count - i); tmp := self[i]; self[i] := self[j]; self[j] := tmp; end; end;   function THelperIntegerDynArray.ToString: string; var value: Integer; begin Result := ''; for value in self do begin Result := Result + ' ' + Format('%4d', [value]); end; Result := '[' + Result.Trim + ']'; end;   var data: TIntegerDynArray;   begin data.FillRange(10); data.Shuffle; writeln('The data before sorting:'); Writeln(data.ToString, #10);   data.CombSort;   writeln('The data after sorting:'); Writeln(data.ToString, #10);   Readln; 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.
#BBC_BASIC
BBC BASIC
DIM test(9) test() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1   shuffles% = 0 WHILE NOT FNsorted(test()) shuffles% += 1 PROCshuffle(test()) ENDWHILE PRINT ;shuffles% " shuffles required to sort "; DIM(test(),1)+1 " items." END   DEF PROCshuffle(d()) LOCAL I% FOR I% = DIM(d(),1)+1 TO 2 STEP -1 SWAP d(I%-1), d(RND(I%)-1) NEXT ENDPROC   DEF FNsorted(d()) LOCAL I% FOR I% = 1 TO DIM(d(),1) IF d(I%) < d(I%-1) THEN = FALSE NEXT = TRUE
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#uBasic.2F4tH
uBasic/4tH
PRINT "Circle sort:" n = FUNC (_InitArray) PROC _ShowArray (n) PROC _Circlesort (n) PROC _ShowArray (n) PRINT   END   _InnerCircle PARAM (2) LOCAL (3) c@ = a@ d@ = b@ e@ = 0   IF c@ = d@ THEN RETURN (0)   DO WHILE c@ < d@ IF @(c@) > @(d@) THEN PROC _Swap (c@, d@) : e@ = e@ + 1 c@ = c@ + 1 d@ = d@ - 1 LOOP   e@ = e@ + FUNC (_InnerCircle (a@, d@)) e@ = e@ + FUNC (_InnerCircle (c@, b@)) RETURN (e@)     _Circlesort PARAM(1) ' Circle sort DO WHILE FUNC (_InnerCircle (0, a@-1)) LOOP RETURN     _Swap PARAM(2) ' Swap two array elements PUSH @(a@) @(a@) = @(b@) @(b@) = POP() RETURN     _InitArray ' Init example array PUSH 4, 65, 2, -31, 0, 99, 2, 83, 782, 1   FOR i = 0 TO 9 @(i) = POP() NEXT   RETURN (i)     _ShowArray PARAM (1) ' Show array subroutine FOR i = 0 TO a@-1 PRINT @(i), NEXT   PRINT 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.
#ActionScript
ActionScript
function gnomeSort(array:Array) { var pos:uint = 0; while(pos < array.length) { if(pos == 0 || array[pos] >= array[pos-1]) pos++; else { var tmp = array[pos]; array[pos] = array[pos-1]; array[pos-1] = tmp; pos--; } } return array; }
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.)
#ActionScript
ActionScript
function countingSort(array:Array, min:int, max:int) { var count:Array = new Array(array.length); for(var i:int = 0; i < count.length;i++)count[i]=0; for(i = 0; i < array.length; i++) { count[array[i]-min] ++; } var j:uint = 0; for(i = min; i <= max; i++) { for(; count[i-min] > 0; count[i-min]--) array[j++] = i; } return array; }
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
#Eiffel
Eiffel
    class COMB_SORT [G -> COMPARABLE]   feature   combsort (ar: ARRAY [G]): ARRAY [G] -- Sorted array in ascending order. require array_not_void: ar /= Void local gap, i: INTEGER swap: G swapped: BOOLEAN shrink: REAL_64 do create Result.make_empty Result.deep_copy (ar) gap := Result.count from until gap = 1 and swapped = False loop from i := Result.lower swapped := False until i + gap > Result.count loop if Result [i] > Result [i + gap] then swap := Result [i] Result [i] := Result [i + gap] Result [i + gap] := swap swapped := True end i := i + 1 end shrink := gap / 1.3 gap := shrink.floor if gap < 1 then gap := 1 end end ensure Result_is_set: Result /= Void 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/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.
#Brat
Brat
bogosort = { list | sorted = list.sort #Kinda cheating here while { list != sorted } { list.shuffle! } list }   p bogosort [15 6 2 9 1 3 41 19]
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h>   bool is_sorted(int *a, int n) { while ( --n >= 1 ) { if ( a[n] < a[n-1] ) return false; } return true; }   void shuffle(int *a, int n) { int i, t, r; for(i=0; i < n; i++) { t = a[i]; r = rand() % n; a[i] = a[r]; a[r] = t; } }   void bogosort(int *a, int n) { while ( !is_sorted(a, n) ) shuffle(a, n); }   int main() { int numbers[] = { 1, 10, 9, 7, 3, 0 }; int i;   bogosort(numbers, 6); for (i=0; i < 6; i++) printf("%d ", numbers[i]); printf("\n"); }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Vlang
Vlang
fn circle_sort(mut a []int, l int, h int, s int) int { mut hi := h mut lo := l mut swaps := s if lo == hi { return swaps } high, low := hi, lo mid := (hi - lo) / 2 for lo < hi { if a[lo] > a[hi] { a[lo], a[hi] = a[hi], a[lo] swaps++ } lo++ hi-- } if lo == hi { if a[lo] > a[hi+1] { a[lo], a[hi+1] = a[hi+1], a[lo] swaps++ } } swaps = circle_sort(mut a, low, low+mid, swaps) swaps = circle_sort(mut a, low+mid+1, high, swaps) return swaps }   fn main() { aa := [ [6, 7, 8, 9, 2, 5, 3, 4, 1], [2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1], ] for a1 in aa { mut a:=a1.clone() println("Original: $a") for circle_sort(mut a, 0, a.len-1, 0) != 0 { // empty block } println("Sorted  : $a\n") } }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Wren
Wren
var circleSort // recursive circleSort = Fn.new { |a, lo, hi, swaps| if (lo == hi) return swaps var high = hi var low = lo var mid = ((hi-lo)/2).floor while (lo < hi) { if (a[lo] > a[hi]) { var t = a[lo] a[lo] = a[hi] a[hi] = t swaps = swaps + 1 } lo = lo + 1 hi = hi - 1 } if (lo == hi) { if (a[lo] > a[hi+1]) { var t = a[lo] a[lo] = a[hi+1] a[hi+1] = t swaps = swaps + 1 } } swaps = circleSort.call(a, low, low + mid, swaps) swaps = circleSort.call(a, low + mid + 1, high, swaps) return swaps }   var as = [ [6, 7, 8, 9, 2, 5, 3, 4, 1], [2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1] ] for (a in as) { System.print("Before: %(a)") while (circleSort.call(a, 0, a.count-1, 0) != 0) {} System.print("After : %(a)") System.print() }
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.
#Ada
Ada
generic type Element_Type is private; type Index is (<>); type Collection is array(Index) of Element_Type; with function "<=" (Left, Right : Element_Type) return Boolean is <>; procedure Gnome_Sort(Item : in out Collection);
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.)
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Counting_Sort is type Data is array (Integer range <>) of Natural; procedure Sort(Item : out Data) is begin for I in Item'range loop Item(I) := I; end loop; end Sort; Stuff : Data(1..140); begin Sort(Stuff); for I in Stuff'range loop Put(Natural'Image(Stuff(I))); end loop; New_Line; end Counting_Sort;
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
#Elena
Elena
import extensions; import system'math; import system'routines;   extension op { combSort() { var list := self.clone();   real gap := list.Length; bool swaps := true; while (gap > 1 || swaps) { gap /= 1.247330950103979r; if (gap<1) { gap := 1 };   int i := 0; swaps := false; while (i + gap.RoundedInt < list.Length) { int igap := i + gap.RoundedInt; if (list[i] > list[igap]) { list.exchange(i,igap); swaps := true }; i += 1 } };   ^ list } }   public program() { var list := new int[]{3, 5, 1, 9, 7, 6, 8, 2, 4 };   console.printLine("before:", list.asEnumerable()); console.printLine("after :", list.combSort().asEnumerable()) }
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.
#C.23
C#
using System; using System.Collections.Generic;   namespace RosettaCode.BogoSort { public static class BogoSorter { public static void Sort<T>(List<T> list) where T:IComparable { while (!list.isSorted()) { list.Shuffle(); } }   private static bool isSorted<T>(this IList<T> list) where T:IComparable { if(list.Count<=1) return true; for (int i = 1 ; i < list.Count; i++) if(list[i].CompareTo(list[i-1])<0) return false; return true; }   private static void Shuffle<T>(this IList<T> list) { Random rand = new Random(); for (int i = 0; i < list.Count; i++) { int swapIndex = rand.Next(list.Count); T temp = list[swapIndex]; list[swapIndex] = list[i]; list[i] = temp; } } }   class TestProgram { static void Main() { List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 }; BogoSorter.Sort(testList); foreach (int i in testList) Console.Write(i + " "); }   } }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#zkl
zkl
fcn circleSort(list){ csort:=fcn(list,lo,hi,swaps){ if(lo==hi) return(swaps); high,low,mid:=hi,lo,(hi-lo)/2; while(lo<hi){ if(list[lo]>list[hi]){ list.swap(lo,hi); swaps+=1; } lo+=1; hi-=1; } if(lo==hi) if (list[lo]>list[hi+1]){ list.swap(lo,hi+1); swaps+=1; } swaps=self.fcn(list,low,low + mid,swaps); swaps=self.fcn(list,low + mid + 1,high,swaps); return(swaps); }; list.println(); while(csort(list,0,list.len()-1,0)){ list.println() } list }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#ZX_Spectrum_Basic
ZX Spectrum Basic
  10 DIM a(100): DIM s(32): RANDOMIZE : LET p=1: GO SUB 3000: GO SUB 2000: GO SUB 4000 20 STOP 1000 IF b=e THEN RETURN 1010 LET s(p)=b: LET s(p+1)=e 1020 IF a(s(p))>a(e) THEN LET t=a(s(p)): LET a(s(p))=a(e): LET a(e)=t: LET c=1 1030 LET s(p)=s(p)+1: LET e=e-1: IF s(p)<e THEN GO TO 1020 1040 LET p=p+2: GO SUB 1000: LET b=s(p-2): LET e=s(p-1): GO SUB 1000: LET p=p-2: RETURN 2000 PRINT "*";: LET b=1: LET e=100: LET c=0: GO SUB 1000: IF c>0 THEN GO TO 2000 2010 CLS : RETURN 3000 FOR x=1 TO 100: LET a(x)=RND: NEXT x: RETURN 4000 FOR x=1 TO 100: PRINT x,a(x): NEXT x: 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.
#ALGOL_68
ALGOL 68
MODE SORTSTRUCT = CHAR;   PROC inplace gnome sort = (REF[]SORTSTRUCT list)REF[]SORTSTRUCT: BEGIN INT i:=LWB list + 1, j:=LWB list + 2; WHILE i <= UPB list DO IF list[i-1] <= list[i] THEN i := j; j+:=1 ELSE SORTSTRUCT swap = list[i-1]; list[i-1]:= list[i]; list[i]:= swap; i-:=1; IF i=LWB list THEN i:=j; j+:=1 FI FI OD; list END;   PROC gnome sort = ([]SORTSTRUCT seq)[]SORTSTRUCT: in place gnome sort(LOC[LWB seq: UPB seq]SORTSTRUCT:=seq);   []SORTSTRUCT char array data = "big fjords vex quick waltz nymph"; print((gnome sort(char array data), new line))
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.)
#ALGOL_68
ALGOL 68
PROC counting sort mm = (REF[]INT array, INT min, max)VOID: ( INT z := LWB array - 1; [min:max]INT count;   FOR i FROM LWB count TO UPB count DO count[i] := 0 OD; FOR i TO UPB array DO count[ array[i] ]+:=1 OD;   FOR i FROM LWB count TO UPB count DO FOR j TO count[i] DO array[z+:=1] := i OD OD );   PROC counting sort = (REF[]INT array)VOID: ( INT min, max; min := max := array[LWB array];   FOR i FROM LWB array + 1 TO UPB array DO IF array[i] < min THEN min := array[i] ELIF array[i] > max THEN max := array[i] FI OD );   # Testing (we suppose the oldest human being is less than 140 years old). #   INT n = 100; INT min age = 0, max age = 140; main: ( [n]INT ages;   FOR i TO UPB ages DO ages[i] := ENTIER (random * ( max age + 1 ) ) OD; counting sort mm(ages, min age, max age); FOR i TO UPB ages DO print((" ", whole(ages[i],0))) OD; print(new line) )
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
#Elixir
Elixir
defmodule Sort do def comb_sort([]), do: [] def comb_sort(input) do comb_sort(List.to_tuple(input), length(input), 0) |> Tuple.to_list end   defp comb_sort(output, 1, 0), do: output defp comb_sort(input, gap, _) do gap = max(trunc(gap / 1.25), 1) {output,swaps} = Enum.reduce(0..tuple_size(input)-gap-1, {input,0}, fn i,{acc,swap} -> if (x = elem(acc,i)) > (y = elem(acc,i+gap)) do {acc |> put_elem(i,y) |> put_elem(i+gap,x), 1} else {acc,swap} end end) comb_sort(output, gap, swaps) end end   (for _ <- 1..20, do: :rand.uniform(20)) |> IO.inspect |> Sort.comb_sort |> IO.inspect