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/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #D | D | cities = [ {"UK", "London"},
{"US", "New York"},
{"US", "Birmingham"},
{"UK", "Birmingham"} ]
IO.inspect Enum.sort(cities)
IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end)
IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end)
IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end) |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | cities = [ {"UK", "London"},
{"US", "New York"},
{"US", "Birmingham"},
{"UK", "Birmingham"} ]
IO.inspect Enum.sort(cities)
IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end)
IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end)
IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end) |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Isabelle | Isabelle | theory LexList
imports
Main
"~~/src/HOL/Library/Char_ord"
"~~/src/HOL/Library/List_Lexorder"
begin
definition ord_ascii_zero :: nat where
"ord_ascii_zero == of_char (CHR ''0'')"
text‹Get the string representation for a single digit.›
definition ascii_of_digit :: "nat ⇒ string" where
"ascii_of_digit n ≡ if n ≥ 10 then undefined else [char_of (n + ord_ascii_zero)]"
fun ascii_of :: "nat ⇒ string" where
"ascii_of n = (if n < 10
then ascii_of_digit n
else ascii_of (n div 10) @ ascii_of_digit (n mod 10))"
lemma ‹ascii_of 123 = ''123''› by code_simp
value ‹sort (map ascii_of (upt 1 13))›
end |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #J | J | task=: [: (/: ":"0) 1 + i.
task 13 |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Java | Java | import java.util.List;
import java.util.stream.*;
public class LexicographicalNumbers {
static List<Integer> lexOrder(int n) {
int first = 1, last = n;
if (n < 1) {
first = n;
last = 1;
}
return IntStream.rangeClosed(first, last)
.mapToObj(Integer::toString)
.sorted()
.map(Integer::valueOf)
.collect(Collectors.toList());
}
public static void main(String[] args) {
System.out.println("In lexicographical order:\n");
int[] ints = {0, 5, 13, 21, -22};
for (int n : ints) {
System.out.printf("%3d: %s\n", n, lexOrder(n));
}
}
} |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Factor | Factor | USING: arrays io kernel prettyprint sequences sorting ;
IN: rosetta-code.sort-three
: sort3 ( b c a -- a b c ) 3array natural-sort first3 ;
"lions, tigers, and"
"bears, oh my!"
"(from the \"Wizard of OZ\")"
sort3 [ print ] tri@
77444 -12 0 sort3 [ . ] tri@ |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #FALSE | FALSE | { [s]waps two variables. (varref; varref) → () }
[
b: { loads the value at the top of the stack into b }
a: { loads the value at the top of the stack into a }
a;; t: { loads the value stored in the variable stored in a (hence the double dereference) into t }
b;; a;: { loads the value stored in the variable stored in b into the variable stored in a }
t; b;: { loads the value stored in t into the variable stored in b }
]s:
{ [p]rints the three variables. }
[
"X = " x;. 10,
"Y = " y;. 10,
"Z = " z;. 10,
]p:
77444 x:
12_ y:
0 z:
p;!
{ if x > y, swap x and y }
x;y;> [xys;!] ?
{ if y > z, swap y and z }
y;z;> [yzs;!] ?
{ if x > y, swap x and y }
x;y;> [xys;!] ?
"After sorting:
"
p;! |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #E | E | /** returns a if it is nonzero, otherwise b() */
def nonzeroOr(a, b) { return if (a.isZero()) { b() } else { a } }
["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] \
.sort(fn a, b {
nonzeroOr(b.size().op__cmp(a.size()),
fn { a.compareToIgnoreCase(b) })
}) |
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
| #Perl | Perl | sub combSort {
my @arr = @_;
my $gap = @arr;
my $swaps = 1;
while ($gap > 1 || $swaps) {
$gap /= 1.25 if $gap > 1;
$swaps = 0;
foreach my $i (0 .. $#arr - $gap) {
if ($arr[$i] > $arr[$i+$gap]) {
@arr[$i, $i+$gap] = @arr[$i+$gap, $i];
$swaps = 1;
}
}
}
return @arr;
} |
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort | Sorting algorithms/Bogosort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Bogosort a list of numbers.
Bogosort simply shuffles a collection randomly until it is sorted.
"Bogosort" is a perversely inefficient algorithm only used as an in-joke.
Its average run-time is O(n!) because the chance that any given shuffle of a set will end up in sorted order is about one in n factorial, and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence.
Its best case is O(n) since a single pass through the elements may suffice to order them.
Pseudocode:
while not InOrder(list) do
Shuffle(list)
done
The Knuth shuffle may be used to implement the shuffle part of this algorithm.
| #Nemerle | Nemerle | using System;
using System.Console;
using Nemerle.Imperative;
module Bogosort
{
public static Bogosort[T] (this x : array[T]) : void
where T : IComparable
{
def rnd = Random();
def shuffle(a)
{
foreach (i in [0 .. (a.Length - 2)])
a[i] <-> a[(rnd.Next(i, a.Length))];
}
def isSorted(b)
{
when (b.Length <= 1) return true;
foreach (i in [1 .. (b.Length - 1)])
when (b[i].CompareTo(b[i - 1]) < 0) return false;
true;
}
def loop()
{
unless (isSorted(x)) {shuffle(x); loop();};
}
loop()
}
Main() : void
{
def sortme = array[1, 5, 3, 6, 7, 3, 8, -2];
sortme.Bogosort();
foreach (i in sortme) Write($"$i ");
}
} |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #BCPL | BCPL | get "libhdr"
let bubblesort(v, length) be
$( let sorted = false
until sorted
$( sorted := true
length := length - 1
for i=0 to length-1
if v!i > v!(i+1)
$( let x = v!i
v!i := v!(i+1)
v!(i+1) := x
sorted := false
$)
$)
$)
let start() be
$( let v = table 10,8,6,4,2,1,3,5,7,9
bubblesort(v, 10)
for i=0 to 9 do writef("%N ", v!i)
wrch('*N')
$) |
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.
| #Groovy | Groovy | def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] }
def checkSwap = { list, i, j = i+1 -> [(list[i] > list[j])].find{ it }.each { makeSwap(list, i, j) } }
def gnomeSort = { input ->
def swap = checkSwap.curry(input)
def index = 1
while (index < input.size()) {
index += (swap(index-1) && index > 1) ? -1 : 1
}
input
} |
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort | Sorting algorithms/Bead sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array of positive integers using the Bead Sort Algorithm.
A bead sort is also known as a gravity sort.
Algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually.
This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
| #Lua | Lua | -- Display message followed by all values of a table in one line
function show (msg, t)
io.write(msg .. ":\t")
for _, v in pairs(t) do io.write(v .. " ") end
print()
end
-- Return a table of random numbers
function randList (length, lo, hi)
local t = {}
for i = 1, length do table.insert(t, math.random(lo, hi)) end
return t
end
-- Count instances of numbers that appear in counting to each list value
function tally (list)
local tal = {}
for k, v in pairs(list) do
for i = 1, v do
if tal[i] then tal[i] = tal[i] + 1 else tal[i] = 1 end
end
end
return tal
end
-- Sort a table of positive integers into descending order
function beadSort (numList)
show("Before sort", numList)
local abacus = tally(numList)
show("Tally list", abacus)
local sorted = tally(abacus)
show("After sort", sorted)
end
-- Main procedure
math.randomseed(os.time())
beadSort(randList(10, 1, 10)) |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The cocktail shaker sort is an improvement on the Bubble Sort.
The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
function cocktailSort( A : list of sortable items )
do
swapped := false
for each i in 0 to length( A ) - 2 do
if A[ i ] > A[ i+1 ] then // test whether the two
// elements are in the wrong
// order
swap( A[ i ], A[ i+1 ] ) // let the two elements
// change places
swapped := true;
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop;
swapped := false
for each i in length( A ) - 2 down to 0 do
if A[ i ] > A[ i+1 ] then
swap( A[ i ], A[ i+1 ] )
swapped := true;
while swapped; // if no elements have been swapped,
// then the list is sorted
Related task
cocktail sort with shifting bounds
| #Fortran | Fortran | PROGRAM COCKTAIL
IMPLICIT NONE
INTEGER :: intArray(10) = (/ 4, 9, 3, -2, 0, 7, -5, 1, 6, 8 /)
WRITE(*,"(A,10I5)") "Unsorted array:", intArray
CALL Cocktail_sort(intArray)
WRITE(*,"(A,10I5)") "Sorted array :", intArray
CONTAINS
SUBROUTINE Cocktail_sort(a)
INTEGER, INTENT(IN OUT) :: a(:)
INTEGER :: i, bottom, top, temp
LOGICAL :: swapped
bottom = 1
top = SIZE(a) - 1
DO WHILE (bottom < top )
swapped = .FALSE.
DO i = bottom, top
IF (array(i) > array(i+1)) THEN
temp = array(i)
array(i) = array(i+1)
array(i+1) = temp
swapped = .TRUE.
END IF
END DO
IF (.NOT. swapped) EXIT
DO i = top, bottom + 1, -1
IF (array(i) < array(i-1)) THEN
temp = array(i)
array(i) = array(i-1)
array(i-1) = temp
swapped = .TRUE.
END IF
END DO
IF (.NOT. swapped) EXIT
bottom = bottom + 1
top = top - 1
END DO
END SUBROUTINE Cocktail_sort
END PROGRAM COCKTAIL |
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.)
| #Nim | Nim | proc countingSort[T](a: var openarray[T]; min, max: int) =
let range = max - min + 1
var count = newSeq[T](range)
var z = 0
for i in 0 ..< a.len: inc count[a[i] - min]
for i in min .. max:
for j in 0 ..< count[i - min]:
a[z] = i
inc z
var a = @[5, 3, 1, 7, 4, 1, 1, 20]
countingSort(a, 1, 20)
echo a |
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.)
| #Objeck | Objeck |
bundle Default {
class Cocktail {
function : Main(args : String[]) ~ Nil {
values := [9, 7, 10, 2, 9, 7, 4, 3, 10, 2, 7, 10];
CountingSort(values, 2, 10);
each(i : values) {
values[i]->PrintLine();
};
}
function : CountingSort(array : Int[], min : Int, max : Int) ~ Nil {
count := Int->New[max - min + 1];
each(i : array) {
number := array[i];
v := count[number - min];
count[number - min] := v + 1;
};
z := 0;
for(i := min; i <= max; i += 1;) {
while(count[i - min] > 0) {
array[z] := i;
z += 1;
v := count[i - min]
count[i - min] := v - 1;
};
};
}
}
}
|
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
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
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #ALGOL_W | ALGOL W | begin % sort a disjoint sub-set of a list %
% Quicksorts in-place the array of integers v, from lb to ub %
procedure quicksort ( integer array v( * )
; integer value lb, ub
) ;
if ub > lb then begin
% more than one element, so must sort %
integer left, right, pivot;
left := lb;
right := ub;
% choosing the middle element of the array as the pivot %
pivot := v( left + ( ( right + 1 ) - left ) div 2 );
while begin
while left <= ub and v( left ) < pivot do left := left + 1;
while right >= lb and v( right ) > pivot do right := right - 1;
left <= right
end do begin
integer swap;
swap := v( left );
v( left ) := v( right );
v( right ) := swap;
left := left + 1;
right := right - 1
end while_left_le_right ;
quicksort( v, lb, right );
quicksort( v, left, ub )
end quicksort ;
% Quicksorts in-place the array of integers v, using %
% the indxexes in unsortedIndexes which has bounds lb to ub %
% it is assumed all elements of unsortedIndexes are in the %
% range for subscripts of v %
procedure indexedQuicksort ( integer array v, unsortedIndexes ( * )
; integer value lb, ub
) ;
if ub > lb then begin
% more than one element, so must sort %
integer array indexes ( lb :: ub );
integer left, right, pivot, p;
% sort the indexes %
for i := lb until ub do indexes( i ) := unsortedIndexes( i );
quicksort( indexes, lb, ub );
% sort the indexed items of the v array %
left := lb;
right := ub;
% choosing the middle element of the array as the pivot %
p := left + ( ( ( right + 1 ) - left ) div 2 );
pivot := v( indexes( p ) );
while begin
while left <= ub and v( indexes( left ) ) < pivot do left := left + 1;
while right >= lb and v( indexes( right ) ) > pivot do right := right - 1;
left <= right
end do begin
integer swap;
swap := v( indexes( left ) );
v( indexes( left ) ) := v( indexes( right ) );
v( indexes( right ) ) := swap;
left := left + 1;
right := right - 1
end while_left_le_right ;
indexedQuicksort( v, indexes, lb, right );
indexedQuicksort( v, indexes, left, ub )
end indexedQuicksort ;
begin % task %
integer array indexes ( 0 :: 2 );
integer array values ( 0 :: 7 );
integer aPos;
aPos := 0;
for v := 7, 6, 5, 4, 3, 2, 1, 0 do begin
values( aPos ) := v;
aPos := aPos + 1
end for_v ;
indexes( 0 ) := 6;
indexes( 1 ) := 1;
indexes( 2 ) := 7;
i_w := 1; s_w := 0; % set output formatting %
write( "[" );
for v := 0 until 7 do writeon( " ", values( v ) );
writeon( " ]" );
indexedQuicksort( values, indexes, 0, 2 );
writeon( " -> [" );
for v := 0 until 7 do writeon( " ", values( v ) );
writeon( " ]" )
end
end. |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #Elixir | Elixir | cities = [ {"UK", "London"},
{"US", "New York"},
{"US", "Birmingham"},
{"UK", "Birmingham"} ]
IO.inspect Enum.sort(cities)
IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end)
IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end)
IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end) |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #Erlang | Erlang | # According to section 21.18 of the reference manual, Sort is not stable (it's a Shell sort).
# However, SortingPerm is stable. We will see it on an example, showing indexes of elements after the sort.
n := 20;
L := List([1 .. n], i -> Random("AB"));
# "AABABBBABBABAABABBAB"
p := SortingPerm(L);
# (3,10,15,17,18,19,9,14,7,13,6,12,16,8,4)(5,11)
a := Permuted(L, p);;
b := Permuted([1 .. n], p);;
PrintArray(TransposedMat(List([1 .. n], i -> [a[i], b[i]])));
# [ [ 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B' ],
# [ 1, 2, 4, 8, 11, 13, 14, 16, 19, 3, 5, 6, 7, 9, 10, 12, 15, 17, 18, 20 ] ] |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #F.23 | F# | # According to section 21.18 of the reference manual, Sort is not stable (it's a Shell sort).
# However, SortingPerm is stable. We will see it on an example, showing indexes of elements after the sort.
n := 20;
L := List([1 .. n], i -> Random("AB"));
# "AABABBBABBABAABABBAB"
p := SortingPerm(L);
# (3,10,15,17,18,19,9,14,7,13,6,12,16,8,4)(5,11)
a := Permuted(L, p);;
b := Permuted([1 .. n], p);;
PrintArray(TransposedMat(List([1 .. n], i -> [a[i], b[i]])));
# [ [ 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B' ],
# [ 1, 2, 4, 8, 11, 13, 14, 16, 19, 3, 5, 6, 7, 9, 10, 12, 15, 17, 18, 20 ] ] |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #Factor | Factor | # According to section 21.18 of the reference manual, Sort is not stable (it's a Shell sort).
# However, SortingPerm is stable. We will see it on an example, showing indexes of elements after the sort.
n := 20;
L := List([1 .. n], i -> Random("AB"));
# "AABABBBABBABAABABBAB"
p := SortingPerm(L);
# (3,10,15,17,18,19,9,14,7,13,6,12,16,8,4)(5,11)
a := Permuted(L, p);;
b := Permuted([1 .. n], p);;
PrintArray(TransposedMat(List([1 .. n], i -> [a[i], b[i]])));
# [ [ 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B' ],
# [ 1, 2, 4, 8, 11, 13, 14, 16, 19, 3, 5, 6, 7, 9, 10, 12, 15, 17, 18, 20 ] ] |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Ksh | Ksh |
#!/bin/ksh
# Sort numbers lexicographically
# # Variables:
#
integer N=${1:-13}
# # Functions:
#
# # Function _fillarray(arr, N) - fill assoc. array 1 -> N
#
function _fillarray {
typeset _arr ; nameref _arr="$1"
typeset _N ; integer _N=$2
typeset _i _st _en ; integer _i _st _en
(( ! _N )) && _arr=0 && return
(( _N<0 )) && _st=${_N} && _en=1
(( _N>0 )) && _st=1 && _en=${_N}
for ((_i=_st; _i<=_en; _i++)); do
_arr[${_i}]=${_i}
done
}
######
# main #
######
set -a -s -A arr
typeset -A arr
_fillarray arr ${N}
print -- ${arr[*]} |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #jq | jq | def sort_range($a;$b): [range($a;$b)] | sort_by(tostring);
# Example
# jq's index origin is 0, so ...
sort_range(1;14) |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Julia | Julia | lexorderedsequence(n) = sort(collect(n > 0 ? (1:n) : n:1), lt=(a,b) -> string(a) < string(b))
for i in [0, 5, 13, 21, -32]
println(lexorderedsequence(i))
end
|
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #FreeBASIC | FreeBASIC | #macro sort_three( x, y, z )
if x>y then swap x, y
if y>z then swap y, z
if x>y then swap x, y
#endmacro
'demonstrate this for strings
dim as string x = "lions, tigers, and"
dim as string y = "bears, oh my!"
dim as string z = "(from the ""Wizard of OZ"")"
sort_three(x,y,z)
print x
print y
print z : print
'demonstrate this for signed integers
dim as integer a = 77444
dim as integer b = -12
dim as integer c = 0
sort_three(a,b,c)
print a
print b
print c |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Forth | Forth | \ sort 3 integers
VARIABLE X VARIABLE Y VARIABLE Z
: VARS@ ( --- n n n) X @ Y @ Z @ ; \ read variables
: VARS! ( n n n -- ) Z ! Y ! X ! ; \ store variables
: ?SWAP ( a b -- a b) \ conditional swap
2DUP < IF SWAP THEN ;
: SORT3INTS ( a b c -- c b a) ?SWAP >R ?SWAP R> ?SWAP ; |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #EGL | EGL | program SortExample
function main()
test1 string[] = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
test1.sort(sortFunction);
SysLib.writeStdout("Test 1:");
for(i int from 1 to test1.getSize())
SysLib.writeStdout(test1[i]);
end
test2 string[] = ["Cat", "apple", "Adam", "zero", "Xmas", "quit", "Level", "add", "Actor", "base", "butter"];
test2.sort(sortFunction);
SysLib.writeStdout("Test 2:");
for(i int from 1 to test2.getSize())
SysLib.writeStdout(test2[i]);
end
end
function sortFunction(a any in, b any in) returns (int)
result int = (b as string).length() - (a as string).length();
if (result == 0)
case
when ((a as string).toLowerCase() > (b as string).toLowerCase())
result = 1;
when ((a as string).toLowerCase() < (b as string).toLowerCase())
result = -1;
otherwise
result = 0;
end
end
return result;
end
end |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #Elena | Elena | import extensions;
import system'routines;
import system'culture;
public program()
{
var items := new string[]{ "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
console.printLine("Unsorted: ", items.asEnumerable());
console.printLine("Descending length: ", items.clone()
.sort:(p,n => p.Length > n.Length).asEnumerable());
console.printLine("Ascending order: ", items.clone()
.sort:(p,n => p.toUpper(invariantLocale) < n.toUpper(invariantLocale)).asEnumerable())
} |
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
| #Phix | Phix | with javascript_semantics
function comb_sort(sequence s)
integer gap = length(s)-1
while 1 do
gap = max(floor(gap/1.3),1)
integer swapped = 0
for i=1 to length(s)-gap do
object si = s[i]
if si>s[i+gap] then
s[i] = s[i+gap]
s[i+gap] = si
swapped = 1
end if
end for
if gap=1 and swapped=0 then exit end if
end while
return s
end function
?comb_sort(shuffle(tagset(10)))
|
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
import java.util.List
method isSorted(list = List) private static returns boolean
if list.isEmpty then
return isTrue
it = list.iterator
last = Comparable it.next
loop label i_ while it.hasNext
current = Comparable it.next
if last.compareTo(current) > 0 then
return isFalse
last = current
end i_
return isTrue
method bogoSort(list = List) private static
loop label s_ while \isSorted(list)
Collections.shuffle(list)
end s_
return
method main(args = String[]) public constant
samples = [int 31, 41, 59, 26, 53, 58, 97, 93, 23, 84]
alst = ArrayList(samples.length)
loop iv = 0 to samples.length - 1
alst.add(Integer(samples[iv]))
end iv
say 'unsorted:' alst.toString
bogoSort(alst)
say 'sorted: ' alst.toString
return
method isTrue public static returns boolean
return 1 == 1
method isFalse public static returns boolean
return \isTrue
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #C | C | #include <stdio.h>
void bubble_sort (int *a, int n) {
int i, t, j = n, s = 1;
while (s) {
s = 0;
for (i = 1; i < j; i++) {
if (a[i] < a[i - 1]) {
t = a[i];
a[i] = a[i - 1];
a[i - 1] = t;
s = 1;
}
}
j--;
}
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
bubble_sort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 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.
| #Haskell | Haskell | gnomeSort [] = []
gnomeSort (x:xs) = gs [x] xs
where
gs vv@(v:vs) (w:ws)
| v<=w = gs (w:vv) ws
| otherwise = gs vs (w:v:ws)
gs [] (y:ys) = gs [y] ys
gs xs [] = reverse xs
-- keeping the first argument of gs in reverse order avoids the deterioration into cubic behaviour |
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort | Sorting algorithms/Bead sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array of positive integers using the Bead Sort Algorithm.
A bead sort is also known as a gravity sort.
Algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually.
This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | beadsort[ a ] := Module[ { m, sorted, s ,t },
sorted = a; m = Max[a]; t=ConstantArray[0, {m,m} ];
If[ Min[a] < 0, Print["can't sort"]];
For[ i = 1, i < Length[a], i++, t[[i,1;;a[[i]]]]=1 ]
For[ i = 1 ,i <= m, i++, s = Total[t[[;;,i]]];
t[[ ;; , i]] = 0; t[[1 ;; s , i]] = 1; ]
For[ i=1,i<=Length[a],i++, sorted[[i]] = Total[t[[i,;;]]]; ]
Print[sorted];
]
beadsort[{2,1,5,3,6}] |
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort | Sorting algorithms/Bead sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array of positive integers using the Bead Sort Algorithm.
A bead sort is also known as a gravity sort.
Algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually.
This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method bead_sort(harry = Rexx[]) public static binary returns Rexx[]
MIN_ = 'MIN'
MAX_ = 'MAX'
beads = Rexx 0
beads[MIN_] = 0
beads[MAX_] = 0
loop val over harry
-- collect occurences of beads in indexed string indexed on value
if val < beads[MIN_] then beads[MIN_] = val -- keep track of min value
if val > beads[MAX_] then beads[MAX_] = val -- keep track of max value
beads[val] = beads[val] + 1
end val
harry_sorted = Rexx[harry.length]
bi = 0
loop xx = beads[MIN_] to beads[MAX_]
-- extract beads in value order and insert in result array
if beads[xx] == 0 then iterate xx
loop for beads[xx]
harry_sorted[bi] = xx
bi = bi + 1
end
end xx
return harry_sorted
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
unsorted = [734, 3, 1, 24, 324, -1024, -666, -1, 0, 324, 32, 0, 432, 42, 3, 4, 1, 1]
sorted = bead_sort(unsorted)
say arrayToString(unsorted)
say arrayToString(sorted)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method arrayToString(harry = Rexx[]) private static
list = Rexx ''
loop vv over harry
list = list vv
end vv
return '['list.space(1, ',')']'
|
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The cocktail shaker sort is an improvement on the Bubble Sort.
The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
function cocktailSort( A : list of sortable items )
do
swapped := false
for each i in 0 to length( A ) - 2 do
if A[ i ] > A[ i+1 ] then // test whether the two
// elements are in the wrong
// order
swap( A[ i ], A[ i+1 ] ) // let the two elements
// change places
swapped := true;
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop;
swapped := false
for each i in length( A ) - 2 down to 0 do
if A[ i ] > A[ i+1 ] then
swap( A[ i ], A[ i+1 ] )
swapped := true;
while swapped; // if no elements have been swapped,
// then the list is sorted
Related task
cocktail sort with shifting bounds
| #FreeBASIC | FreeBASIC | ' version 21-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Sub cocktailsort(bs() As Long)
' sort from lower bound to the highter bound
' array's can have subscript range from -2147483648 to +2147483647
Dim As Long lb = LBound(bs)
Dim As Long ub = UBound(bs) -1
Dim As Long done, i
Do
done = 0 ' going up
For i = lb To ub
If bs(i) > bs(i +1) Then
Swap bs(i), bs(i +1)
done = 1
End If
Next
ub = ub -1
If done = 0 Then Exit Do ' 0 means the array is sorted
done = 0 ' going down
For i = ub To lb Step -1
If bs(i) > bs(i +1) Then
Swap bs(i), bs(i +1)
done = 1
End If
Next
lb = lb +1
Loop Until done = 0 ' 0 means the array is sorted
End Sub
' ------=< MAIN >=------
Dim As Long i, array(-7 To 7)
Dim As Long a = LBound(array), b = UBound(array)
Randomize Timer
For i = a To b : array(i) = i : Next
For i = a To b ' little shuffle
Swap array(i), array(Int(Rnd * (b - a +1)) + a)
Next
Print "unsorted ";
For i = a To b : Print Using "####"; array(i); : Next : Print
cocktailsort(array()) ' sort the array
Print " sorted ";
For i = a To b : Print Using "####"; array(i); : Next : Print
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort | Sorting algorithms/Counting sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Counting sort. This is a way of sorting integers when the minimum and maximum value are known.
Pseudocode
function countingSort(array, min, max):
count: array of (max - min + 1) elements
initialize count with 0
for each number in array do
count[number - min] := count[number - min] + 1
done
z := 0
for i from min to max do
while ( count[i - min] > 0 ) do
array[z] := i
z := z+1
count[i - min] := count[i - min] - 1
done
done
The min and max can be computed apart, or be known a priori.
Note: we know that, given an array of integers, its maximum and minimum values can be always found; but if we imagine the worst case for an array that can hold up to 32 bit integers, we see that in order to hold the counts, an array of up to 232 elements may be needed. I.E.: we need to hold a count value up to 232-1, which is a little over 4.2 Gbytes. So the counting sort is more practical when the range is (very) limited, and minimum and maximum values are known a priori. (However, as a counterexample, the use of sparse arrays minimizes the impact of the memory usage, as well as removing the need of having to know the minimum and maximum values a priori.)
| #OCaml | OCaml | let counting_sort_array arr lo hi =
let count = Array.make (hi-lo+1) 0 in
Array.iter (fun i -> count.(i-lo) <- count.(i-lo) + 1) arr;
Array.concat (Array.to_list (Array.mapi (fun i x -> Array.make x (lo+i)) count)) |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #11l | 11l | nums = [2,4,3,1,2]
nums.sort() |
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
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
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #APL | APL |
∇SDS[⎕]∇
∇
[0] Z←I SDS L
[1] L[I[⍋I]]←Z[⍋Z←L[I←∪I]]
[2] Z←L
∇
|
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
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
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
-- disjointSort :: [Int] -> [Int] -> [Int]
on disjointSort(ixs, xs)
set ks to sort(ixs)
script nth -- 1-based index
on |λ|(k)
item (succ(k)) of xs
end |λ|
end script
set dct to mapFromList(zip(ks, sort(map(nth, ks))))
script build
on |λ|(x, i)
set mb to lookupDict(pred(i) as string, dct)
if Nothing of mb then
x
else
|Just| of mb
end if
end |λ|
end script
map(build, xs)
end disjointSort
on run
disjointSort({6, 1, 7}, {7, 6, 5, 4, 3, 2, 1, 0})
end run
-- GENERIC FUNCTIONS ----------------------------------------------------
-- Just :: a -> Maybe a
on Just(x)
{type:"Maybe", Nothing:false, Just:x}
end Just
-- Nothing :: Maybe a
on Nothing()
{type:"Maybe", Nothing:true}
end Nothing
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
-- lookupDict :: a -> Dict -> Maybe b
on lookupDict(k, dct)
set ca to current application
set v to (ca's NSDictionary's dictionaryWithDictionary:dct)'s objectForKey:k
if v ≠ missing value then
Just(item 1 of ((ca's NSArray's arrayWithObject:v) as list))
else
Nothing()
end if
end lookupDict
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- mapFromList :: [(k, v)] -> Dict
on mapFromList(kvs)
set tpl to unzip(kvs)
script
on |λ|(x)
x as string
end |λ|
end script
(current application's NSDictionary's ¬
dictionaryWithObjects:(|2| of tpl) ¬
forKeys:map(result, |1| of tpl)) as record
end mapFromList
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- pred :: Enum a => a -> a
on pred(x)
x - 1
end pred
-- sort :: Ord a => [a] -> [a]
on sort(xs)
((current application's NSArray's arrayWithArray:xs)'s ¬
sortedArrayUsingSelector:"compare:") as list
end sort
-- succ :: Enum a => a -> a
on succ(x)
1 + x
end succ
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to xs's |λ|()
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
-- unzip :: [(a,b)] -> ([a],[b])
on unzip(xys)
set xs to {}
set ys to {}
repeat with xy in xys
set end of xs to |1| of xy
set end of ys to |2| of xy
end repeat
return Tuple(xs, ys)
end unzip
-- zip :: [a] -> [b] -> [(a, b)]
on zip(xs, ys)
zipWith(Tuple, xs, ys)
end zip
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(|length|(xs), |length|(ys))
if 1 > lng then return {}
set xs_ to take(lng, xs) -- Allow for non-finite
set ys_ to take(lng, ys) -- generators like cycle etc
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs_, item i of ys_)
end repeat
return lst
end tell
end zipWith |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #Fortran | Fortran | # According to section 21.18 of the reference manual, Sort is not stable (it's a Shell sort).
# However, SortingPerm is stable. We will see it on an example, showing indexes of elements after the sort.
n := 20;
L := List([1 .. n], i -> Random("AB"));
# "AABABBBABBABAABABBAB"
p := SortingPerm(L);
# (3,10,15,17,18,19,9,14,7,13,6,12,16,8,4)(5,11)
a := Permuted(L, p);;
b := Permuted([1 .. n], p);;
PrintArray(TransposedMat(List([1 .. n], i -> [a[i], b[i]])));
# [ [ 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B' ],
# [ 1, 2, 4, 8, 11, 13, 14, 16, 19, 3, 5, 6, 7, 9, 10, 12, 15, 17, 18, 20 ] ] |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #FreeBASIC | FreeBASIC | # According to section 21.18 of the reference manual, Sort is not stable (it's a Shell sort).
# However, SortingPerm is stable. We will see it on an example, showing indexes of elements after the sort.
n := 20;
L := List([1 .. n], i -> Random("AB"));
# "AABABBBABBABAABABBAB"
p := SortingPerm(L);
# (3,10,15,17,18,19,9,14,7,13,6,12,16,8,4)(5,11)
a := Permuted(L, p);;
b := Permuted([1 .. n], p);;
PrintArray(TransposedMat(List([1 .. n], i -> [a[i], b[i]])));
# [ [ 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B' ],
# [ 1, 2, 4, 8, 11, 13, 14, 16, 19, 3, 5, 6, 7, 9, 10, 12, 15, 17, 18, 20 ] ] |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #GAP | GAP | # According to section 21.18 of the reference manual, Sort is not stable (it's a Shell sort).
# However, SortingPerm is stable. We will see it on an example, showing indexes of elements after the sort.
n := 20;
L := List([1 .. n], i -> Random("AB"));
# "AABABBBABBABAABABBAB"
p := SortingPerm(L);
# (3,10,15,17,18,19,9,14,7,13,6,12,16,8,4)(5,11)
a := Permuted(L, p);;
b := Permuted([1 .. n], p);;
PrintArray(TransposedMat(List([1 .. n], i -> [a[i], b[i]])));
# [ [ 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B' ],
# [ 1, 2, 4, 8, 11, 13, 14, 16, 19, 3, 5, 6, 7, 9, 10, 12, 15, 17, 18, 20 ] ] |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Kotlin | Kotlin | // Version 1.2.51
fun lexOrder(n: Int): List<Int> {
var first = 1
var last = n
if (n < 1) {
first = n
last = 1
}
return (first..last).map { it.toString() }.sorted().map { it.toInt() }
}
fun main(args: Array<String>) {
println("In lexicographical order:\n")
for (n in listOf(0, 5, 13, 21, -22)) {
println("${"%3d".format(n)}: ${lexOrder(n)}")
}
} |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Lambdatalk | Lambdatalk |
1) lexicographically sorting a sequence of numbers
{S.sort before 1 2 3 4 5 6 7 8 9 10 11 12 13}
-> 1 10 11 12 13 2 3 4 5 6 7 8 9
2) lexicographically sorting an array of numbers
{A.sort! before {A.new 1 2 3 4 5 6 7 8 9 10 11 12 13}}
-> [1,10,11,12,13,2,3,4,5,6,7,8,9]
|
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Fortran | Fortran | TYPE(MONGREL)
INTEGER TYPEIS
INTEGER VI
REAL VF
CHARACTER*(enuff) VC
...etc...
END TYPE MONGREL
TYPE (MONGREL) DOG |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | {$mode objFPC}
generic procedure sort<T>(var X, Y: T);
procedure swap;
var
Z: T;
begin
Z := X;
X := Y;
Y := Z
end;
begin
if X > Y then
begin
swap
end
end;
generic procedure sort<T>(var X, Y, Z: T);
begin
specialize sort<T>(X, Y);
specialize sort<T>(X, Z);
specialize sort<T>(Y, Z)
end;
generic procedure print<T>(const X, Y, Z: T);
begin
writeLn('X = ', X);
writeLn('Y = ', Y);
writeLn('Z = ', Z)
end;
{ === MAIN ============================================================= }
var
A, B, C: string;
I, J, K: integer;
P, Q, R: real;
begin
A := 'lions, tigers, and';
B := 'bears, oh my!';
C := '(from the "Wizard of OZ")';
specialize sort<string>(A, B, C);
specialize print<string>(A, B, C);
writeLn;
I := 77444;
J := -12;
K := 0;
specialize sort<integer>(I, J, K);
specialize print<integer>(I, J, K);
writeLn;
P := 12.34;
Q := -56.78;
R := 9.01;
specialize sort<real>(P, Q, R);
specialize print<real>(P, Q, R)
end. |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #Elixir | Elixir | strs = ~w[this is a set of strings to sort This Is A Set Of Strings To Sort]
comparator = fn s1,s2 -> if String.length(s1)==String.length(s2),
do: String.downcase(s1) <= String.downcase(s2),
else: String.length(s1) >= String.length(s2) end
IO.inspect Enum.sort(strs, comparator)
# or
IO.inspect Enum.sort_by(strs, fn str -> {-String.length(str), String.downcase(str)} 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
| #PHP | PHP | function combSort($arr){
$gap = count($arr);
$swap = true;
while ($gap > 1 || $swap){
if($gap > 1) $gap /= 1.25;
$swap = false;
$i = 0;
while($i+$gap < count($arr)){
if($arr[$i] > $arr[$i+$gap]){
list($arr[$i], $arr[$i+$gap]) = array($arr[$i+$gap],$arr[$i]);
$swap = true;
}
$i++;
}
}
return $arr;
} |
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort | Sorting algorithms/Bogosort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Bogosort a list of numbers.
Bogosort simply shuffles a collection randomly until it is sorted.
"Bogosort" is a perversely inefficient algorithm only used as an in-joke.
Its average run-time is O(n!) because the chance that any given shuffle of a set will end up in sorted order is about one in n factorial, and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence.
Its best case is O(n) since a single pass through the elements may suffice to order them.
Pseudocode:
while not InOrder(list) do
Shuffle(list)
done
The Knuth shuffle may be used to implement the shuffle part of this algorithm.
| #Nim | Nim | import random
randomize()
proc isSorted[T](s: openarray[T]): bool =
var last = low(T)
for c in s:
if c < last:
return false
last = c
return true
proc bogoSort[T](a: var openarray[T]) =
while not isSorted a: shuffle a
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
bogoSort a
echo a |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace RosettaCode.BubbleSort
{
public static class BubbleSortMethods
{
//The "this" keyword before the method parameter identifies this as a C# extension
//method, which can be called using instance method syntax on any generic list,
//without having to modify the generic List<T> code provided by the .NET framework.
public static void BubbleSort<T>(this List<T> list) where T : IComparable
{
bool madeChanges;
int itemCount = list.Count;
do
{
madeChanges = false;
itemCount--;
for (int i = 0; i < itemCount; i++)
{
if (list[i].CompareTo(list[i + 1]) > 0)
{
T temp = list[i + 1];
list[i + 1] = list[i];
list[i] = temp;
madeChanges = true;
}
}
} while (madeChanges);
}
}
//A short test program to demonstrate the BubbleSort. The compiler will change the
//call to testList.BubbleSort() into one to BubbleSortMethods.BubbleSort<T>(testList).
class Program
{
static void Main()
{
List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };
testList.BubbleSort();
foreach (var t in testList) Console.Write(t + " ");
}
}
} |
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.
| #Haxe | Haxe | class GnomeSort {
@:generic
public static function sort<T>(arr:Array<T>) {
var i = 1;
var j = 2;
while (i < arr.length) {
if (Reflect.compare(arr[i - 1], arr[i]) <= 0) {
i = j++;
} else {
var temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
if (--i == 0) {
i = j++;
}
}
}
}
}
class Main {
static function main() {
var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0];
var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3,
3.5, 0.0, -4.1, -9.5];
var stringArray = ['We', 'hold', 'these', 'truths', 'to',
'be', 'self-evident', 'that', 'all',
'men', 'are', 'created', 'equal'];
Sys.println('Unsorted Integers: ' + integerArray);
GnomeSort.sort(integerArray);
Sys.println('Sorted Integers: ' + integerArray);
Sys.println('Unsorted Floats: ' + floatArray);
GnomeSort.sort(floatArray);
Sys.println('Sorted Floats: ' + floatArray);
Sys.println('Unsorted Strings: ' + stringArray);
GnomeSort.sort(stringArray);
Sys.println('Sorted Strings: ' + stringArray);
}
} |
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort | Sorting algorithms/Bead sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array of positive integers using the Bead Sort Algorithm.
A bead sort is also known as a gravity sort.
Algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually.
This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
| #Nim | Nim | proc beadSort[T](a: var openarray[T]) =
var max = low(T)
var sum = 0
for x in a:
if x > max: max = x
var beads = newSeq[int](max * a.len)
for i in 0 ..< a.len:
for j in 0 ..< a[i]:
beads[i * max + j] = 1
for j in 0 ..< max:
sum = 0
for i in 0 ..< a.len:
sum += beads[i * max + j]
beads[i * max + j] = 0
for i in a.len - sum ..< a.len:
beads[i * max + j] = 1
for i in 0 ..< a.len:
var j = 0
while j < max and beads[i * max + j] > 0: inc j
a[i] = j
var a = @[5, 3, 1, 7, 4, 1, 1, 20]
beadSort a
echo a |
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort | Sorting algorithms/Bead sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array of positive integers using the Bead Sort Algorithm.
A bead sort is also known as a gravity sort.
Algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually.
This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
| #OCaml | OCaml | let rec columns l =
match List.filter ((<>) []) l with
[] -> []
| l -> List.map List.hd l :: columns (List.map List.tl l)
let replicate n x = Array.to_list (Array.make n x)
let bead_sort l =
List.map List.length (columns (columns (List.map (fun e -> replicate e 1) l))) |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The cocktail shaker sort is an improvement on the Bubble Sort.
The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
function cocktailSort( A : list of sortable items )
do
swapped := false
for each i in 0 to length( A ) - 2 do
if A[ i ] > A[ i+1 ] then // test whether the two
// elements are in the wrong
// order
swap( A[ i ], A[ i+1 ] ) // let the two elements
// change places
swapped := true;
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop;
swapped := false
for each i in length( A ) - 2 down to 0 do
if A[ i ] > A[ i+1 ] then
swap( A[ i ], A[ i+1 ] )
swapped := true;
while swapped; // if no elements have been swapped,
// then the list is sorted
Related task
cocktail sort with shifting bounds
| #Gambas | Gambas | Public Sub Main()
Dim siCount, siRev, siProcess As Short
Dim bSorting As Boolean
Dim byToSort As Byte[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 154, 147, 102, 46, 183, 24,
120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77]
Print "To sort: -"
ShowWorking(byToSort)
Print
Repeat
bSorting = False
siRev = byToSort.Max - 1
For siCount = 0 To byToSort.Max - 1
siProcess = siCount
GoSub Check
siProcess = siRev
GoSub Check
Dec siRev
Next
If bSorting Then ShowWorking(byToSort)
Until bSorting = False
Return
Check:
If byToSort[siProcess] > byToSort[siProcess + 1] Then
Swap byToSort[siProcess], byToSort[siProcess + 1]
bSorting = True
Endif
Return
End
'-----------------------------------------
Public Sub ShowWorking(byToSort As Byte[])
Dim siCount As Byte
For siCount = 0 To byToSort.Max
Print Str(byToSort[siCount]);
If siCount <> byToSort.Max Then Print ",";
Next
Print
End |
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort | Sorting algorithms/Counting sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Counting sort. This is a way of sorting integers when the minimum and maximum value are known.
Pseudocode
function countingSort(array, min, max):
count: array of (max - min + 1) elements
initialize count with 0
for each number in array do
count[number - min] := count[number - min] + 1
done
z := 0
for i from min to max do
while ( count[i - min] > 0 ) do
array[z] := i
z := z+1
count[i - min] := count[i - min] - 1
done
done
The min and max can be computed apart, or be known a priori.
Note: we know that, given an array of integers, its maximum and minimum values can be always found; but if we imagine the worst case for an array that can hold up to 32 bit integers, we see that in order to hold the counts, an array of up to 232 elements may be needed. I.E.: we need to hold a count value up to 232-1, which is a little over 4.2 Gbytes. So the counting sort is more practical when the range is (very) limited, and minimum and maximum values are known a priori. (However, as a counterexample, the use of sparse arrays minimizes the impact of the memory usage, as well as removing the need of having to know the minimum and maximum values a priori.)
| #Octave | Octave | function r = counting_sort(arr, minval, maxval)
r = arr;
z = 1;
for i = minval:maxval
cnt = sum(arr == i);
while( cnt-- > 0 )
r(z++) = i;
endwhile
endfor
endfunction |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #4D | 4D | ARRAY INTEGER($nums;0)
APPEND TO ARRAY($nums;2)
APPEND TO ARRAY($nums;4)
APPEND TO ARRAY($nums;3)
APPEND TO ARRAY($nums;1)
APPEND TO ARRAY($nums;2)
SORT ARRAY($nums) ` sort in ascending order
SORT ARRAY($nums;<) ` sort in descending order |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #8th | 8th |
[ 10,2,100 ] ' n:cmp a:sort . cr
|
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
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
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #Arturo | Arturo | sortDisjoint: function [data, indices][
result: new data
inds: new indices
sort 'inds
vals: new []
loop inds 'i -> 'vals ++ result\[i]
sort 'vals
loop.with:'j inds 'i -> result\[i]: vals\[j]
return result
]
d: [7 6 5 4 3 2 1 0]
print sortDisjoint d [6 1 7] |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #Go | Go | def cityList = ['UK London', 'US New York', 'US Birmingham', 'UK Birmingham',].asImmutable()
[
'Sort by city': { city -> city[4..-1] },
'Sort by country': { city -> city[0..3] },
].each{ String label, Closure orderBy ->
println "\n\nBefore ${label}"
cityList.each { println it }
println "\nAfter ${label}"
cityList.sort(false, orderBy).each{ println it }
} |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #Groovy | Groovy | def cityList = ['UK London', 'US New York', 'US Birmingham', 'UK Birmingham',].asImmutable()
[
'Sort by city': { city -> city[4..-1] },
'Sort by country': { city -> city[0..3] },
].each{ String label, Closure orderBy ->
println "\n\nBefore ${label}"
cityList.each { println it }
println "\nAfter ${label}"
cityList.sort(false, orderBy).each{ println it }
} |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Lua | Lua | function lexNums (limit)
local numbers = {}
for i = 1, limit do
table.insert(numbers, tostring(i))
end
table.sort(numbers)
return numbers
end
local numList = lexNums(13)
print(table.concat(numList, " ")) |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Function lexicographical(N) {
const nl$=Chr$(13)+Chr$(10)
If N<>0 then {
if N=1 then =(1,) : Exit
Document A$
For k=1 to N-1
A$=Str$(k,"")+{
}
Next k
A$=Str$(N,"")
Method A$, "SetBinaryCompare"
Sort A$
Flush
\\ convert strings to numbers in one statement
\\ in stack of values
Data Param(Replace$(nl$,",", a$))
\\ return stack as array
=Array([])
} else =(0,) ' empty array
}
Print lexicographical(5) ' 1 2 3 4 5
Print lexicographical(13) ' 1 10 11 12 13 2 3 4 5 6 7 8 9
Print lexicographical(21) ' 1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9
Print lexicographical(-22) ' -1 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -2 -20 -21 -22 -3 -4 -5 -6 -7 -8 -9 0 1
}
Checkit
Module Checkit {
Function lexicographical$(N) {
const nl$=Chr$(13)+Chr$(10)
If N<>0 then {
if N=1 then =(1,) : Exit
Document A$
For k=1 to N-1
A$=Str$(k,"")+{
}
Next k
A$=Str$(N,"")
\\ by default id TextCompare, so 0 an 1 comes first in -22
Method A$, "SetBinaryCompare"
Sort A$
Flush
="["+Replace$(nl$," ", a$)+"]"
} else =("",) ' empty array
}
Print lexicographical$(5) ' [1 2 3 4 5]
Print lexicographical$(13) ' [1 10 11 12 13 2 3 4 5 6 7 8 9]
Print lexicographical$(21) '[1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9]
Print lexicographical$(-22) ' [-1 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -2 -20 -21 -22 -3 -4 -5 -6 -7 -8 -9 0 1]
}
Checkit
|
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | SortBy[Range[13],ToString] |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Free_Pascal | Free Pascal | {$mode objFPC}
generic procedure sort<T>(var X, Y: T);
procedure swap;
var
Z: T;
begin
Z := X;
X := Y;
Y := Z
end;
begin
if X > Y then
begin
swap
end
end;
generic procedure sort<T>(var X, Y, Z: T);
begin
specialize sort<T>(X, Y);
specialize sort<T>(X, Z);
specialize sort<T>(Y, Z)
end;
generic procedure print<T>(const X, Y, Z: T);
begin
writeLn('X = ', X);
writeLn('Y = ', Y);
writeLn('Z = ', Z)
end;
{ === MAIN ============================================================= }
var
A, B, C: string;
I, J, K: integer;
P, Q, R: real;
begin
A := 'lions, tigers, and';
B := 'bears, oh my!';
C := '(from the "Wizard of OZ")';
specialize sort<string>(A, B, C);
specialize print<string>(A, B, C);
writeLn;
I := 77444;
J := -12;
K := 0;
specialize sort<integer>(I, J, K);
specialize print<integer>(I, J, K);
writeLn;
P := 12.34;
Q := -56.78;
R := 9.01;
specialize sort<real>(P, Q, R);
specialize print<real>(P, Q, R)
end. |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #Erlang | Erlang |
-module( sort_using_custom_comparator ).
-export( [task/0] ).
task() ->
lists:sort( fun longest_first_case_insensitive/2, ["this", "is", "a", "set", "of", "strings", "to", "sort", "This", "Is", "A", "Set", "Of", "Strings", "To", "Sort"] ).
longest_first_case_insensitive( String1, String2 ) when erlang:length(String1) =:= erlang:length(String2) -> string:to_lower(String1) < string:to_lower(String2);
longest_first_case_insensitive( String1, String2 ) when erlang:length(String1) =< erlang:length(String2) -> false;
longest_first_case_insensitive( _String1, _String2 ) -> true.
|
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
| #PicoLisp | PicoLisp | (de combSort (Lst)
(let (Gap (length Lst) Swaps NIL)
(while (or (> Gap 1) Swaps)
(setq Gap (max 1 (/ (* Gap 4) 5)))
(off Swaps)
(use Lst
(for (G (cdr (nth Lst Gap)) G (cdr G))
(when (> (car Lst) (car G))
(xchg Lst G)
(on Swaps) )
(pop 'Lst) ) ) ) )
Lst ) |
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.
| #Oberon-2 | Oberon-2 | MODULE Bogo;
IMPORT Out, Random;
VAR a: ARRAY 10 OF INTEGER;
PROCEDURE Init;
VAR i: INTEGER;
BEGIN
FOR i := 0 TO LEN(a) - 1 DO
a[i] := i + 1;
END;
END Init;
PROCEDURE Sorted(VAR a: ARRAY OF INTEGER): BOOLEAN;
VAR i: INTEGER;
BEGIN
IF LEN(a) <= 1 THEN
RETURN TRUE;
END;
FOR i := 1 TO LEN(a) - 1 DO
IF (a[i] < a[i - 1]) THEN
RETURN FALSE;
END;
END;
RETURN TRUE;
END Sorted;
PROCEDURE Shuffle*(VAR a: ARRAY OF INTEGER);
VAR n, t, r: INTEGER;
BEGIN
FOR n := 0 TO LEN(a) - 1 DO
r := Random.Roll(n);
t := a[n];
a[n] := a[r];
a[r] := t;
END;
END Shuffle;
BEGIN
Init;
Shuffle(a);
WHILE ~Sorted(a) DO
Shuffle(a);
END;
FOR i := 0 TO LEN(a) - 1 DO
Out.Int(a[i], 0);
Out.String(" ");
END;
Out.Ln;
END Bogo. |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #C.2B.2B | C++ | g++ -std=c++11 bubble.cpp
|
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main() #: demonstrate various ways to sort a list and string
demosort(gnomesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
procedure gnomesort(X,op) #: return sorted list
local i,j
op := sortop(op,X) # select how and what we sort
j := (i := 2) + 1 # translation of pseudo code
while i <= *X do {
if op(X[i],X[i-1]) then {
X[i] :=: X[i -:= 1]
if i > 1 then next
}
j := (i := j) + 1
}
return X
end |
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort | Sorting algorithms/Bead sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array of positive integers using the Bead Sort Algorithm.
A bead sort is also known as a gravity sort.
Algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually.
This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
| #Octave | Octave | function sorted = beadsort(a)
sorted = a;
m = max(a);
if ( any(a < 0) )
error("can't sort");
endif
t = zeros(m, m);
for i = 1:numel(a)
t(i, 1:a(i)) = 1;
endfor
for i = 1:m
s = sum(t(:, i));
t(:, i) = 0;
t(1:s, i) = 1;
endfor
for i = 1:numel(a)
sorted(i) = sum(t(i, :));
endfor
endfunction
beadsort([5, 7, 1, 3, 1, 1, 20]) |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The cocktail shaker sort is an improvement on the Bubble Sort.
The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
function cocktailSort( A : list of sortable items )
do
swapped := false
for each i in 0 to length( A ) - 2 do
if A[ i ] > A[ i+1 ] then // test whether the two
// elements are in the wrong
// order
swap( A[ i ], A[ i+1 ] ) // let the two elements
// change places
swapped := true;
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop;
swapped := false
for each i in length( A ) - 2 down to 0 do
if A[ i ] > A[ i+1 ] then
swap( A[ i ], A[ i+1 ] )
swapped := true;
while swapped; // if no elements have been swapped,
// then the list is sorted
Related task
cocktail sort with shifting bounds
| #Go | Go | package main
import "fmt"
func main() {
a := []int{170, 45, 75, -90, -802, 24, 2, 66}
fmt.Println("before:", a)
cocktailSort(a)
fmt.Println("after: ", a)
}
func cocktailSort(a []int) {
last := len(a) - 1
for {
swapped := false
for i := 0; i < last; i++ {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
return
}
swapped = false
for i := last - 1; i >= 0; i-- {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
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.)
| #Oz | Oz | declare
proc {CountingSort Arr Min Max}
Count = {Array.new Min Max 0}
Z = {NewCell {Array.low Arr}}
in
%% fill frequency array
for J in {Array.low Arr}..{Array.high Arr} do
Number = Arr.J
in
Count.Number := Count.Number + 1
end
%% recreate array from frequencies
for I in Min..Max do
for C in 1..Count.I do
Arr.(@Z) := I
Z := @Z + 1
end
end
end
A = {Tuple.toArray unit(3 1 4 1 5 9 2 6 5)}
in
{CountingSort A 1 9}
{Show {Array.toRecord unit A}} |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program integerSort64.s with selection sort */
/*******************************************/
/* 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 selectionSort
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
/******************************************************************/
/* selection sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first element */
/* x2 contains the number of element */
selectionSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
mov x3,x1 // start index i
sub x7,x2,1 // compute n - 1
1: // start loop
mov x4,x3
add x5,x3,1 // init index 2
2:
ldr x1,[x0,x4,lsl 3] // load value A[mini]
ldr x6,[x0,x5,lsl 3] // load value A[j]
cmp x6,x1 // compare value
csel x4,x5,x4,lt // j -> mini
add x5,x5,1 // increment index j
cmp x5,x2 // end ?
blt 2b // no -> loop
cmp x4,x3 // mini <> j ?
beq 3f // no
ldr x1,[x0,x4,lsl 3] // yes swap A[i] A[mini]
ldr x6,[x0,x3,lsl 3]
str x1,[x0,x3,lsl 3]
str x6,[x0,x4,lsl 3]
3:
add x3,x3,1 // increment i
cmp x3,x7 // end ?
blt 1b // no -> loop
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* 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 conversion10 // 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
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/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #Action.21 | Action! | INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit
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 Test(INT ARRAY a INT size BYTE order)
PrintE("Array before sort:")
PrintArray(a,size)
SortI(a,size,order)
PrintE("Array after sort:")
PrintArray(a,size)
PutE()
RETURN
PROC Main()
DEFINE ASCENDING="0"
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]
Put(125) PutE() ;clear screen
Test(a,10,ASCENDING)
Test(b,21,ASCENDING)
Test(c,8,ASCENDING)
Test(d,12,ASCENDING)
RETURN |
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
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
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #AutoHotkey | AutoHotkey | Sort_disjoint_sublist(Values, Indices){
A := [], B:=[], C := [], D := []
for k, v in Indices
A[v] := 1 , B[Values[v]] := v
for k, v in A
C.Push(k)
for k, v in B
D.Push(k)
for k, v in D
Values[C[A_Index]] := D[A_Index]
return Values
} |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #Haskell | Haskell | import java.util.Arrays;
import java.util.Comparator;
public class RJSortStability {
public static void main(String[] args) {
String[] cityList = { "UK London", "US New York", "US Birmingham", "UK Birmingham", };
String[] cn = cityList.clone();
System.out.println("\nBefore sort:");
for (String city : cn) {
System.out.println(city);
}
// sort by city
Arrays.sort(cn, new Comparator<String>() {
public int compare(String lft, String rgt) {
return lft.substring(4).compareTo(rgt.substring(4));
}
});
System.out.println("\nAfter sort on city:");
for (String city : cn) {
System.out.println(city);
}
cn = cityList.clone();
System.out.println("\nBefore sort:");
for (String city : cn) {
System.out.println(city);
}
// sort by country
Arrays.sort(cn, new Comparator<String>() {
public int compare(String lft, String rgt) {
return lft.substring(0, 2).compareTo(rgt.substring(0, 2));
}
});
System.out.println("\nAfter sort on country:");
for (String city : cn) {
System.out.println(city);
}
System.out.println();
}
} |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Microsoft_Small_Basic | Microsoft Small Basic | ' Lexicographical numbers - 25/07/2018
xx="000000000000000"
For n=1 To 3
nn=Text.GetSubText(" 5 13 21",n*4-3,4)
ll=Text.GetLength(nn)
For i=1 To nn
t[i]=i
EndFor
i=nn-1
k=0
For i=i To 1 Step -1
ok=1
For j=1 To i
k=j+1
tj=Text.GetSubText(Text.Append(t[j],xx),1,ll)
tk=Text.GetSubText(Text.Append(t[k],xx),1,ll)
If tj>tk Then
w=t[j]
t[j]=t[k]
t[k]=w
ok=0
EndIf
EndFor
If ok=1 Then
Goto exitfor
EndIf
EndFor
exitfor:
x=""
For i=1 To nn
x=x+","+t[i]
EndFor
TextWindow.WriteLine(nn+":"+Text.GetSubTextToEnd(x,2))
EndFor |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #MUMPS | MUMPS |
SortLexographically(n)
new array,i,j
for i=1:1:n set array(i_" ")=""
for set j=$order(array(j)) quit:j="" write j
quit
|
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Nim | Nim | import algorithm, sequtils
for n in [0, 5, 13, 21, -22]:
let s = if n > 1: toSeq(1..n) else: toSeq(countdown(1, n))
echo s.sortedByIt($it) |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Go | Go | package main
import (
"fmt"
"log"
"sort"
)
var (
stringsIn = []string{
`lions, tigers, and`,
`bears, oh my!`,
`(from the "Wizard of OZ")`}
intsIn = []int{77444, -12, 0}
)
func main() {
{
// initialize three vars
x, y, z := stringsIn[0], stringsIn[1], stringsIn[2]
// I. Task suggested technique, move values to array (slice).
// It's consise and relies on library code.
s := []string{x, y, z}
sort.Strings(s)
x, y, z = s[0], s[1], s[2]
// validate
if x > y || y > z {
log.Fatal()
}
// II. Likely fastest technique, minimizing tests and data movement.
// Least consise though, hardest to understand, and most chance to make
// a coding mistake.
x, y, z = stringsIn[0], stringsIn[1], stringsIn[2] // (initialize)
if x < y {
switch {
case y < z:
case x < z:
y, z = z, y
default:
x, y, z = z, x, y
}
} else {
switch {
case x < z:
x, y = y, x
case z < y:
x, z = z, x
default:
x, y, z = y, z, x
}
}
if x > y || y > z { // (validate)
log.Fatal()
}
// III. A little more consise than II, easier to understand, almost
// as fast.
x, y, z = stringsIn[0], stringsIn[1], stringsIn[2] // (initialize)
if x > y {
x, y = y, x
}
if y > z {
y, z = z, y
}
if x > y {
x, y = y, x
}
if x > y || y > z { // (validate)
log.Fatal()
}
fmt.Println("sorted strings:")
fmt.Println(" ", x)
fmt.Println(" ", y)
fmt.Println(" ", z)
fmt.Println("original data:")
fmt.Println(" ", stringsIn[0])
fmt.Println(" ", stringsIn[1])
fmt.Println(" ", stringsIn[2])
}
// same techniques, with integer test case
{
// task suggested technique
x, y, z := intsIn[0], intsIn[1], intsIn[2] // (initialize)
s := []int{x, y, z}
sort.Ints(s)
x, y, z = s[0], s[1], s[2]
if x > y || y > z { // (validate)
log.Fatal()
}
// minimizing data movement
x, y, z = intsIn[0], intsIn[1], intsIn[2] // (initialize)
if x < y {
switch {
case y < z:
case x < z:
y, z = z, y
default:
x, y, z = z, x, y
}
} else {
switch {
case x < z:
x, y = y, x
case z < y:
x, z = z, x
default:
x, y, z = y, z, x
}
}
if x > y || y > z { // (validate)
log.Fatal()
}
// three swaps
x, y, z = intsIn[0], intsIn[1], intsIn[2] // (initialize)
if x > y {
x, y = y, x
}
if y > z {
y, z = z, y
}
if x > y {
x, y = y, x
}
if x > y || y > z { // (validate)
log.Fatal()
}
fmt.Println("sorted ints:", x, y, z)
fmt.Println("original data:", intsIn)
}
// To put any of these techniques in a function, a function could just
// take three values and return them sorted.
{
sort3 := func(x, y, z int) (int, int, int) {
if x > y {
x, y = y, x
}
if y > z {
y, z = z, y
}
if x > y {
x, y = y, x
}
return x, y, z
}
x, y, z := intsIn[0], intsIn[1], intsIn[2] // (initialize)
x, y, z = sort3(x, y, z)
if x > y || y > z { // (validate)
log.Fatal()
}
}
// Alternatively, a function could take pointers
{
sort3 := func(x, y, z *int) {
if *x > *y {
*x, *y = *y, *x
}
if *y > *z {
*y, *z = *z, *y
}
if *x > *y {
*x, *y = *y, *x
}
}
x, y, z := intsIn[0], intsIn[1], intsIn[2] // (initialize)
sort3(&x, &y, &z)
if x > y || y > z { // (validate)
log.Fatal()
}
}
} |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #Euphoria | Euphoria | include sort.e
include wildcard.e
include misc.e
function my_compare(sequence a, sequence b)
if length(a)!=length(b) then
return -compare(length(a),length(b))
else
return compare(lower(a),lower(b))
end if
end function
sequence strings
strings = reverse({ "Here", "are", "some", "sample", "strings", "to", "be", "sorted" })
puts(1,"Unsorted:\n")
pretty_print(1,strings,{2})
puts(1,"\n\nSorted:\n")
pretty_print(1,custom_sort(routine_id("my_compare"),strings),{2}) |
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
| #PL.2FI | PL/I |
/* From the pseudocode. */
comb_sort: procedure (A);
declare A(*) fixed;
declare t fixed;
declare (i, gap) fixed binary (31);
declare swaps bit (1) aligned;
gap = hbound(A,1) - lbound(A,1); /* initialize the gap size. */
do until (gap <= 1 & swaps);
/* update the gap value for a next comb. */
put skip data (gap);
gap = gap / 1.25e0;
put skip data (gap);
swaps = '1'b;
/* a single "comb" over the array. */
do i = lbound(A,1) by 1 until (i + gap >= hbound(A,1));
if A(i) > A(i+gap) then
do;
t = A(i); A(i) = A(i+gap); A(i+gap) = t;
swaps = '0'b; /* Flag a swap has occurred, so */
/* the list is not guaranteed sorted. */
end;
end;
end;
end comb_sort;
|
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.
| #OCaml | OCaml | let rec is_sorted comp = function
| e1 :: e2 :: r -> comp e1 e2 <= 0 && is_sorted comp (e2 :: r)
| _ -> true
(* Fisher-Yates shuffle on lists; uses temp array *)
let shuffle l =
let ar = Array.of_list l in
for n = Array.length ar - 1 downto 1 do
let k = Random.int (n+1) in
let temp = ar.(k) in (* swap ar.(k) and ar.(n) *)
ar.(k) <- ar.(n);
ar.(n) <- temp
done;
Array.to_list ar
let rec bogosort li =
if is_sorted compare li then
li
else
bogosort (shuffle li) |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Clojure | Clojure | (ns bubblesort
(:import java.util.ArrayList))
(defn bubble-sort
"Sort in-place.
arr must implement the Java List interface and should support
random access, e.g. an ArrayList."
([arr] (bubble-sort compare arr))
([cmp arr]
(letfn [(swap! [i j]
(let [t (.get arr i)]
(doto arr
(.set i (.get arr j))
(.set j t))))
(sorter [stop-i]
(let [changed (atom false)]
(doseq [i (range stop-i)]
(if (pos? (cmp (.get arr i) (.get arr (inc i))))
(do
(swap! i (inc i))
(reset! changed true))))
@changed))]
(doseq [stop-i (range (dec (.size arr)) -1 -1)
:while (sorter stop-i)])
arr)))
(println (bubble-sort (ArrayList. [10 9 8 7 6 5 4 3 2 1]))) |
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.
| #Io | Io | List do(
gnomeSortInPlace := method(
idx := 1
while(idx <= size,
if(idx == 0 or at(idx) > at(idx - 1)) then(
idx = idx + 1
) else(
swapIndices(idx, idx - 1)
idx = idx - 1
)
)
self)
)
lst := list(5, -1, -4, 2, 9)
lst gnomeSortInPlace println # ==> list(-4, -1, 2, 5, 9) |
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort | Sorting algorithms/Bead sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array of positive integers using the Bead Sort Algorithm.
A bead sort is also known as a gravity sort.
Algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually.
This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
| #ooRexx | ooRexx | in='10 -12 1 0 999 8 2 2 4 4'
Do i=1 To words(in)
z.i=word(in,i)
End
n=i-1
init=0
Call minmax
beads.=0;
Do i=1 To words(in)
z=z.i
beads.z+=1
End
j=0
Do i=lo To hi
Do While beads.i>0
j+=1
s.j=i
beads.i-=1
End;
End;
Call show ' Input:',z.,n
Call show 'Sorted:',s.,n
Exit
minmax:
Do i=1 To n
If init=0 Then Do
init=1
lo=z.i
hi=z.i
End
Else Do
lo=min(lo,z.i)
hi=max(hi,z.i)
End
End
Return
show: Procedure Expose n
Use Arg txt,a.
ol=txtg>
Do i=1 To n
ol=ol format(a.i,3)
End
Say ol
Return |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The cocktail shaker sort is an improvement on the Bubble Sort.
The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
function cocktailSort( A : list of sortable items )
do
swapped := false
for each i in 0 to length( A ) - 2 do
if A[ i ] > A[ i+1 ] then // test whether the two
// elements are in the wrong
// order
swap( A[ i ], A[ i+1 ] ) // let the two elements
// change places
swapped := true;
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop;
swapped := false
for each i in length( A ) - 2 down to 0 do
if A[ i ] > A[ i+1 ] then
swap( A[ i ], A[ i+1 ] )
swapped := true;
while swapped; // if no elements have been swapped,
// then the list is sorted
Related task
cocktail sort with shifting bounds
| #Groovy | Groovy | def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] }
def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find{ it }.each { makeSwap(a, i, j) } }
def cocktailSort = { list ->
if (list == null || list.size() < 2) return list
def n = list.size()
def swap = checkSwap.curry(list)
while (true) {
def swapped = (0..(n-2)).any(swap) && ((-2)..(-n)).any(swap)
if ( ! swapped ) break
}
list
} |
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.)
| #PARI.2FGP | PARI/GP | countingSort(v,mn,mx)={
my(u=vector(#v),i=0);
for(n=mn,mx,
for(j=1,#v,if(v[j]==n,u[i++]=n))
);
u
}; |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #ActionScript | ActionScript | //Comparison function must returns Numbers even though it deals with integers.
function compare(x:int, y:int):Number
{
return Number(x-y);
}
var nums:Vector.<int> = Vector.<int>([5,12,3,612,31,523,1,234,2]);
nums.sort(compare); |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #Ada | Ada | with Gnat.Heap_Sort_G;
procedure Integer_Sort is
-- Heap sort package requires data to be in index values starting at
-- 1 while index value 0 is used as temporary storage
type Int_Array is array(Natural range <>) of Integer;
Values : Int_Array := (0,1,8,2,7,3,6,4,5);
-- define move and less than subprograms for use by the heap sort package
procedure Move_Int(From : Natural; To : Natural) is
begin
Values(To) := Values(From);
end Move_Int;
function Lt_Int(Left, Right : Natural) return Boolean is
begin
return Values(Left) < Values (Right);
end Lt_Int;
-- Instantiate the generic heap sort package
package Heap_Sort is new Gnat.Heap_Sort_G(Move_Int, Lt_Int);
begin
Heap_Sort.Sort(8);
end Integer_Sort;
requires an Ada05 compiler, e.g GNAT GPL 2007
with Ada.Containers.Generic_Array_Sort;
procedure Integer_Sort is
--
type Int_Array is array(Natural range <>) of Integer;
Values : Int_Array := (0,1,8,2,7,3,6,4,5);
-- Instantiate the generic sort package from the standard Ada library
procedure Sort is new Ada.Containers.Generic_Array_Sort
(Index_Type => Natural,
Element_Type => Integer,
Array_Type => Int_Array);
begin
Sort(Values);
end Integer_Sort; |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
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
Object identifiers (OID)
Task
Show how to sort a list of OIDs, in their natural sort order.
Details
An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number.
Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields.
Test case
Input (list of strings)
Output (list of strings)
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11150.3.4.0.1
Related tasks
Natural sorting
Sort using a custom comparator
| #11l | 11l | V data = [
‘1.3.6.1.4.1.11.2.17.19.3.4.0.10’,
‘1.3.6.1.4.1.11.2.17.5.2.0.79’,
‘1.3.6.1.4.1.11.2.17.19.3.4.0.4’,
‘1.3.6.1.4.1.11150.3.4.0.1’,
‘1.3.6.1.4.1.11.2.17.19.3.4.0.1’,
‘1.3.6.1.4.1.11150.3.4.0’
]
V delim = ‘.’ // to get round ‘bug in MSVC 2017’[https://developercommunity.visualstudio.com/t/bug-with-operator-in-c/565417]
L(s) sorted(data, key' x -> x.split(:delim).map(Int))
print(s) |
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
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
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0) : REM Ascending
DIM list%(7) : list%() = 7, 6, 5, 4, 3, 2, 1, 0
DIM indices%(2) : indices%() = 6, 1, 7
PROCsortdisjoint(list%(), indices%())
PRINT FNshowlist(list%())
END
DEF PROCsortdisjoint(l%(), i%())
LOCAL C%, i%, n%, t%()
n% = DIM(i%(),1)
DIM t%(n%)
FOR i% = 0 TO n%
t%(i%) = l%(i%(i%))
NEXT
C% = n% + 1
CALL Sort%, i%(0)
CALL Sort%, t%(0)
FOR i% = 0 TO n%
l%(i%(i%)) = t%(i%)
NEXT
ENDPROC
DEF FNshowlist(l%())
LOCAL i%, o$
o$ = "["
FOR i% = 0 TO DIM(l%(),1)
o$ += STR$(l%(i%)) + ", "
NEXT
= LEFT$(LEFT$(o$)) + "]" |
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
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
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #Bracmat | Bracmat | 7 6 5 4 3 2 1 0:?values
& 6 1 7:?indices
& 0:?sortedValues:?sortedIndices
& whl
' ( !indices:%?i ?indices
& !values:? [!i %@?value ?
& (!value.)+!sortedValues:?sortedValues
& (!i.)+!sortedIndices:?sortedIndices
)
& whl
' ( !sortedIndices:(?i.)+?sortedIndices
& !values:?A [!i %@? ?Z
& !sortedValues:(?value.)+?sortedValues
& !A !value !Z:?values
)
& out$!values; |
http://rosettacode.org/wiki/Sort_stability | Sort stability |
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
When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.
Example
In this table of countries and cities, a stable sort on the second column, the cities, would keep the US Birmingham above the UK Birmingham.
(Although an unstable sort might, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would guarantee it).
UK London
US New York
US Birmingham
UK Birmingham
Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item (since the order of the elements having the same first word – UK or US – would be maintained).
Task
Examine the documentation on any in-built sort routines supplied by a language.
Indicate if an in-built routine is supplied
If supplied, indicate whether or not the in-built routine is stable.
(This Wikipedia table shows the stability of some common sort routines).
| #Icon_and_Unicon | Icon and Unicon | import java.util.Arrays;
import java.util.Comparator;
public class RJSortStability {
public static void main(String[] args) {
String[] cityList = { "UK London", "US New York", "US Birmingham", "UK Birmingham", };
String[] cn = cityList.clone();
System.out.println("\nBefore sort:");
for (String city : cn) {
System.out.println(city);
}
// sort by city
Arrays.sort(cn, new Comparator<String>() {
public int compare(String lft, String rgt) {
return lft.substring(4).compareTo(rgt.substring(4));
}
});
System.out.println("\nAfter sort on city:");
for (String city : cn) {
System.out.println(city);
}
cn = cityList.clone();
System.out.println("\nBefore sort:");
for (String city : cn) {
System.out.println(city);
}
// sort by country
Arrays.sort(cn, new Comparator<String>() {
public int compare(String lft, String rgt) {
return lft.substring(0, 2).compareTo(rgt.substring(0, 2));
}
});
System.out.println("\nAfter sort on country:");
for (String city : cn) {
System.out.println(city);
}
System.out.println();
}
} |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Perl | Perl | printf("%4d: [%s]\n", $_, join ',', sort $_ > 0 ? 1..$_ : $_..1) for 13, 21, -22 |
http://rosettacode.org/wiki/Sort_numbers_lexicographically | Sort numbers lexicographically |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Given an integer n, return 1──►n (inclusive) in lexicographical order.
Show all output here on this page.
Example
Given 13,
return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
| #Phix | Phix | with javascript_semantics
function lexicographic_order(sequence s)
return extract(s,custom_sort(apply(s,sprint),tagset(length(s))))
end function
?lexicographic_order({1,0})
?lexicographic_order(tagset(5))
?lexicographic_order(tagset(13))
?lexicographic_order(tagset(21,1,2))
?lexicographic_order(tagset(11,-21,4))
?lexicographic_order({1.25, -6, -10, 9, -11.3, 13, -3, 0})
|
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Haskell | Haskell | import Data.List (sort)
sortedTriple
:: Ord a
=> (a, a, a) -> (a, a, a)
sortedTriple (x, y, z) =
let [a, b, c] = sort [x, y, z]
in (a, b, c)
sortedListfromTriple
:: Ord a
=> (a, a, a) -> [a]
sortedListfromTriple (x, y, z) = sort [x, y, z]
-- TEST ----------------------------------------------------------------------
main :: IO ()
main = do
print $
sortedTriple
("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")")
print $
sortedListfromTriple
("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")")
print $ sortedTriple (77444, -12, 0)
print $ sortedListfromTriple (77444, -12, 0) |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #F.23 | F# | let myCompare (s1:string) (s2:string) =
match compare s2.Length s1.Length with
| 0 -> compare (s1.ToLower()) (s2.ToLower())
| X -> X
let strings = ["Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"]
let sortedStrings = List.sortWith myCompare strings
printfn "%A" sortedStrings |
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
| #PowerShell | PowerShell | function CombSort ($a) {
$l = $a.Length
$gap = 11
while( $gap -lt $l )
{
$gap = [Math]::Floor( $gap*1.3 )
}
if( $l -gt 1 )
{
$hasChanged = $true
:outer while ($hasChanged -or ( $gap -gt 1 ) ) {
$count = 0
$hasChanged = $false
if( $gap -gt 1 ) {
$gap = [Math]::Floor( $gap/1.3 )
} else {
$l--
}
for ($i = 0; $i -lt ( $l - $gap ); $i++) {
if ($a[$i] -gt $a[$i+$gap]) {
$a[$i], $a[$i+$gap] = $a[$i+$gap], $a[$i]
$hasChanged = $true
$count++
}
}
}
}
$a
}
$l = 100; CombSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 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.
| #Oz | Oz | declare
proc {BogoSort Arr}
for while:{Not {InOrder Arr}} do
{Shuffle Arr}
end
end
fun {InOrder Arr}
for I in {Array.low Arr}+1..{Array.high Arr}
return:Return default:true
do
if Arr.(I-1) > Arr.I then {Return false} end
end
end
proc {Shuffle Arr}
Low = {Array.low Arr}
High = {Array.high Arr}
in
for I in High..Low;~1 do
J = Low + {OS.rand} mod (I - Low + 1)
OldI = Arr.I
in
Arr.I := Arr.J
Arr.J := OldI
end
end
X = {Tuple.toArray unit(3 1 4 1 5 9 2 6 5)}
in
{BogoSort X}
{Show {Array.toRecord unit X}} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.