# Question
Title: I need a program where the user inputs an array of doubles and the program outputs the array sorted
**Note: This question was severely edited since I first posted it here. The rules were moved to here, read them before posting any answer to understand the purpose of this. This was the first question created in the category.**

Imagine a lazy user on Stack Overflow asks this question:

> I need a program where the user inputs an array of doubles and the program outputs the array sorted. Could you please give the code?

How could you create a piece of code that will troll this user? Create a piece of code that will appear useful to an inexperienced programmer but is utterly useless in practice.

The winner is the most upvoted answer, except if the answer is somehow not eligible (for eligibility requirements, check the tag wiki description of ). If the previously most upvoted answer is beaten in the future in the number of upvotes after being accepted, the new best answer is accepted and the previous one is unaccepted. In the case of a tie, I will choose the winner at will among the tied ones or just wait a bit more.

Answers that have no code are not eligible. They might be fun and get some upvotes, but they won't be accepted.

Rules can be found at tag description.

Note: This is a question. Please do not take the question and/or answers seriously. More information here.

# Answer
Sometimes the community here doesn't like to help with homework. That's why you are getting so many joke answers. But I like to help. Here is a complete solution in 'C' (since I assume you want to learn "programming", not "scripting" with Java or Ruby). I've included many tips that I wish I had known when I was first learning

```
#include <stdio.h>

//Always use meaningful names for types
typedef unsigned char boolean;
#define True 't'
#define FALSE (!True)

//this is a really neat trick for swapping values efficiently
void swap(long* a,long *b) { *a=*a^*b;*b=*b^*a;*a=*a^*b; }

//Here's a readability improvement
#define until(condition) while(!(condition))

int main(int n, char*args[]){
  double *d;
  int i;
  char input[5];  //should be long enough for most doubles.
  boolean sorted = FALSE;

  //In C, you need to specify the array size beforehand, so ask
  printf("Please enter the length of the array\n");
  gets(input);
  //scan the input string and convert to a value
  sscanf(input,"%s",&input[0]);
  n=(long)atol(input);

  //allocate space, make sure you get the order of arguments right.
  d = calloc(sizeof(double),n);

  //Get and sort the array
  until (sorted) {

     for (i=0;i<n;i++) {
        //It's important to always ask nicely
        printf("Please enter the %d%s array item\n",i,i==1?"st":"th");
        scanf("%lf",d+i);
     }
     //do a compare and exchange sort:
     sorted = !sorted;  //not sorted
     //check all the items
     printf("%d %d\n",i,n);
     for (i=1;i<n;i++) {
        //compare
        if (d[i]<d[i-1]) {
          //exchange
          swap(d+i,d+i-1);
          sorted = FALSE;
        }
     }
     //show results
     printf("The array is%ssorted\n",sorted?" ":" not "); }
  //use the --> "downto operator" for counting downto 0.
  for (;n-->0;) printf("%lf\n",*d++);
  }

```
> 177 votes

# Answer
Here it is in java. It is utter cheating, unacceptable and unfixable because it creates a MySQL database, insert the number there, do a select with an ORDER BY clause and outputs the numbers given by MySQL. In fact, it is MySQL who is doing the sorting, not the program.

```
package sorter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

public class SortingAlgorithm {

    private static final String CREATE_DB = "CREATE DATABASE sorting";
    private static final String DROP_DB = "DROP DATABASE sorting";
    private static final String CREATE_TABLE = "CREATE TABLE sorting.sorting ( num double not null )";

    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        List<Double> doubles = new ArrayList<>(50);
        String typed;
        do {
            typed = JOptionPane.showInputDialog(null, "Type a double:");
            if (typed != null) doubles.add(Double.parseDouble(typed));
        } while (typed != null);

        List<Double> sorted = new ArrayList<>(50);

        try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root")) {
            try (PreparedStatement ps = con.prepareStatement(CREATE_DB)) {
                ps.executeUpdate();
            }
            try (PreparedStatement ps = con.prepareStatement(CREATE_TABLE)) {
                ps.executeUpdate();
            }

            for (Double d : doubles) {
                try (PreparedStatement ps = con.prepareStatement("INSERT INTO sorting.sorting (num) VALUES (" + d + ")")) {
                    ps.executeUpdate();
                }
            }

            try (
                    PreparedStatement ps = con.prepareStatement("SELECT * FROM sorting.sorting ORDER BY num");
                    ResultSet rs = ps.executeQuery())
            {
                while (rs.next()) {
                    sorted.add(rs.getDouble("num"));
                }
            }
            try (PreparedStatement ps = con.prepareStatement(DROP_DB)) {
                ps.executeUpdate();
            }
        }

        JOptionPane.showMessageDialog(null, "The array sorted is: " + sorted);
    }
}

```
> 179 votes

# Answer
# C# - There's no kill like overkill

First of all, dear GiMmEtHaCoDeZ, let's try to break down your task:

1. Read the numbers
2. Sort them
3. Output the sorted numbers.

As "Divide and conquer" is very important strategy when working with software problems, lets tackle them one at a time

# 1. Reading

Another important issue in software is versatility. Since it's not specified how the user will input the numbers, that can happen via the console, via a file, via a web service, etc. Maybe even some method that we can't think of at the moment. So, it's important that our solution will be able to accommodate various types of input. The easiest way to achieve that will be to extract the important part to an interface, let's say

```
public interface IDoubleArrayReader
{
  IEnumerable<double> GetDoubles();

  DoubleArrayReaderType Type {get;}
}

```

where `DoubleArrayReaderType` is an enumeration given with

```
public enum DoubleArrayReaderType
{
  Console,
  File,
  Database,
  Internet,
  Cloud,
  MockService
}

```

It's also important to make the software testable from the ground up, so an implementation of the interface will be

```
public class MockServiceDoubleArrayReader : IDoubleArrayReader
{
    IEnumerable<double> IDoubleArrayReader.GetDoubles()
    {
      Random r = new Random();
      for(int i =0; i<=10; i++)
      {
        yield return r.NextDouble();
      }
    }

    DoubleArrayReaderType IDoubleArrayReader.Type
    {
      get
      {
        return DoubleArrayReaderType.MockService;
      }
    }
}

```

Next, the logical question is how we will know to load the appropriate `IDoubleArrayReader` into the code. That's easy as long as we use a simple factory:

```
public static class DoubleArrayInputOutputFactory
{
  private static Dictionary<DoubleArrayReaderType, IDoubleArrayReader> readers;

  static DoubleArrayInputOutputFactory()
  {
      readers = new Dictionary<DoubleArrayReaderType, IDoubleArrayReader>();
      foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
      {
        try
        {
          var instance = Activator.CreateInstance(type);
          if (instance is IDoubleArrayReader)
          {
            readers.Add((instance as IDoubleArrayReader).Type,
                        (instance as IDoubleArrayReader));
          }
        }
        catch
        {
          continue;
        }
      }
  }

  public static IDoubleArrayReader CreateDoubleArrayReader(DoubleArrayReaderType type)
  {
    return readers[type];
  }
}

```

Note that, we use reflection to load all active readers, so any future extensions will be automatically available Now, in the main body of out code we just do:

```
IDoubleArrayReader reader = DoubleArrayInputOutputFactory
                           .CreateDoubleArrayReader(DoubleArrayReaderType.MockService);
var doubles = reader.GetDoubles();

```

# 2. Processing (sorting)

Now we need to process, i.e. sort the numbers we have acquired. Note that the steps are completely independent of each other, so to the sorting subsystem, it does not matter how the numbers were inputed. Additionally, the sorting behavior is also something that is subject to change, e.g. we might need to input a more efficient sorting algorithm in place. So, naturally, we'll extract the requested processing behaviour in an interface:

```
public interface IDoubleArrayProcessor
{
  IEnumerable<double> ProcessDoubles(IEnumerable<double> input);

  DoubleArrayProcessorType Type {get;}
}

public enum DoubleArrayProcessorType
{
  Sorter,
  Doubler,
  Tripler,
  Quadrupler,
  Squarer
}

```

And the sorting behaviour will just implement the interface:

```
public class SorterDoubleArrayProcessor : IDoubleArrayProcessor
{
    IEnumerable<double> IDoubleArrayProcessor.ProcessDoubles(IEnumerable<double> input)
    {
      var output = input.ToArray();
      Array.Sort(output);
      return output;
    }

    DoubleArrayProcessorType IDoubleArrayProcessor.Type
    {
      get
      {
        return DoubleArrayProcessorType.Sorter;
      }
    }
}

```

Of course, we will need a factory to load and manage the processing instances.

```
public static class DoubleArrayProcessorFactory
{
  private static Dictionary<DoubleArrayProcessorType, IDoubleArrayProcessor> processors;

  static DoubleArrayProcessorFactory()
  {
      processors = new Dictionary<DoubleArrayProcessorType, IDoubleArrayProcessor>();
      foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
      {
        try
        {
          var instance = Activator.CreateInstance(type);
          if (instance is IDoubleArrayProcessor)
          {
            processors.Add((instance as IDoubleArrayProcessor).Type, (instance as IDoubleArrayProcessor));
          }
        }
        catch
        {
          continue;
        }
      }
  }

  public static IDoubleArrayProcessor CreateDoubleArrayProcessor(DoubleArrayProcessorType type)
  {
    return processors[type];
  }

}

```

# 3. Writing the output

Nothing much to say here, as this is a process that mirror the input. In fact, we could combine the reading and writing factories into a single `DoubleArrayInputOutputFactory`, like this:

```
public interface IDoubleArrayWriter
{
  void WriteDoublesArray(IEnumerable<double> doubles);

  DoubleArrayWriterType Type {get;}
}

public enum DoubleArrayWriterType
{
  Console,
  File,
  Internet,
  Cloud,
  MockService,
  Database
}

public class ConsoleDoubleArrayWriter : IDoubleArrayWriter
{
    void IDoubleArrayWriter.WriteDoublesArray(IEnumerable<double> doubles)
    {
      foreach(double @double in doubles)
      {
        Console.WriteLine(@double);
      }
    }

    DoubleArrayWriterType IDoubleArrayWriter.Type
    {
      get
      {
        return DoubleArrayWriterType.Console;
      }
    }
}

public static class DoubleArrayInputOutputFactory
{
  private static Dictionary<DoubleArrayReaderType, IDoubleArrayReader> readers;
  private static Dictionary<DoubleArrayWriterType, IDoubleArrayWriter> writers;

  static DoubleArrayInputOutputFactory()
  {
      readers = new Dictionary<DoubleArrayReaderType, IDoubleArrayReader>();
      writers = new Dictionary<DoubleArrayWriterType, IDoubleArrayWriter>();
      foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
      {
        try
        {
          var instance = Activator.CreateInstance(type);
          if (instance is IDoubleArrayReader)
          {
            readers.Add((instance as IDoubleArrayReader).Type, (instance as IDoubleArrayReader));
          }
        }
        catch
        {
          continue;
        }
      }

      foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
      {
        try
        {
          var instance = Activator.CreateInstance(type);
          if (instance is IDoubleArrayWriter)
          {
            writers.Add((instance as IDoubleArrayWriter).Type, (instance as IDoubleArrayWriter));
          }
        }
        catch
        {
          continue;
        }
      }

  }

  public static IDoubleArrayReader CreateDoubleArrayReader(DoubleArrayReaderType type)
  {
    return readers[type];
  }

  public static IDoubleArrayWriter CreateDoubleArrayWriter(DoubleArrayWriterType type)
  {
    return writers[type];
  }

}

```

# Putting it all together

Finally, our main program will just use all this awesomeness we have already built, so the code will just be:

```
var doubles = reader.GetDoubles();
doubles = processor.ProcessDoubles(doubles);
writer.WriteDoublesArray(doubles);

```

where, e.g. we could define `reader`, `writer` and `processor` using

```
IDoubleArrayReader reader = DoubleArrayInputOutputFactory.CreateDoubleArrayReader(DoubleArrayReaderType.MockService);
IDoubleArrayProcessor processor = DoubleArrayProcessorFactory.CreateDoubleArrayProcessor(DoubleArrayProcessorType.Sorter);
IDoubleArrayWriter writer = DoubleArrayInputOutputFactory.CreateDoubleArrayWriter(DoubleArrayWriterType.Console);

```
> 142 votes

# Answer
Even more literal interpretation:

```
echo " aaehrrty"

```

that is, "the array" sorted.
> 130 votes

# Answer
# Perl

Out of all of the things I've done for CodeGolf.SE, this probably took the most time, at least a few hours.

```
$_[0]=eval<>;
for(0..$#{$_[0]}**2){
 @_[$#_+1]=[\(@{$_[$#_]}),$#{$_[$#_]}+1];
 for(1..$#{$_[$#_]}-$#_){
  if(eval('${'x$#_.'@{$_[$#_]}[$_-1]'.'}'x$#_)>eval('${'x$#_.'@{$_[$#_]}[$_]'.'}'x$#_)){
   ${$_[$#_]}[$#{$_[$#_]}]=$_;
  }
 }
 (${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]-1],${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]])=(${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]],${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]-1]);
}
for(0..~~@{$_[0]}){
 $\.=eval('${'x$#_.'${$_[$#_]}[$_-1]'.'}'x$#_).','
}
$\=~s/,*$//;$\=~s/^,*//;$\="[$\]";
print;

```

Input is of the form `[2,4,5,7,7,3]` and output is of the form `[2,3,4,5,7,7]`.

~~I don't have time to explain now... be back later.~~

Anyways, there is something called an anonymous array in Perl. It is an array, but it has no name. What we do know, however, is a reference (memory location) that points to it. A series of numbers in square brackets creates an anonymous array, and it returns a reference to it.

This answer is built off of a series of anonymous arrays, the references to which are stored in `@_`. The input is turned into an anonymous array. We then create other anonymous arrays, each element of which is a reference to an element in the previous array. Instead of sorting the elements in the array, we sort the pointers to the elements in that array. Also, we create a new array for each step (and more) in the sort operation.
> 106 votes

# Answer
## Python

Gives the user a sorted array by removing all elements not in sorted order from the input array.

```
import sys

sorted = []
for number in map(float, sys.stdin.read().split()):
    if not sorted or number >= sorted[-1]:
         sorted.append(number)
print sorted

```

The algorithm goes through the list only adding each element if it won't make the list unsorted. Thus the output is a sorted list, just not one that's contains all the elements of the original list. If the op just checks if the list is in sorted order he may not notice that the output is missing values.
> 79 votes

# Answer
# Bash, 54 characters

A lot of answers using slow inefficient languages like C and Python... let's speed things up a bit by offering a solution in the mother of all scripting languages: Bash.

I know what you're thinking - Bash can't even handle floating point arithmetic, so how is it going to sort, right? Well, behold, my implementation of the mighty SleepSort algorithm:

```
#!/bin/bash

for i in $@; do echo -n $(sleep $i)$i' '& done
echo "Leveraging the power of your $(grep -c ^processor /proc/cpuinfo) cores to \
sort optimally by spawning $(jobs -l | wc -l) concurrent sorting threads..."
wait
echo -e "\nThe array sorted."

```

The program is provided with input as commandline arguments. Sample run:

```
> ./sleepsort.sh 7 1 4 3 2.752 6.9 0.01 0.02
Leveraging the power of your 4 cores to optimally by spawning 8 concurrent sorting threads...
0.01 0.02 1 2.752 3 4 6.9 7
The array sorted.

```

This also has the advantage of perhaps being the shortest of all working algorithms presented here. That's right - **one mighty line of bash**, using only bash builtins and not calling any external binaries (that is, if you don't count the purely optional verbose output). Unlike the bogosorts, its runtime is deterministic.

Tip: An effective optimisation is to divide the input numbers by a factor before sorting. Implementation is left up to the reader.

## Edit:

Shortened 54-char golf version with less pretty-printing:

```
#!/bin/sh
for i in $@;do echo $(sleep $i)$i&done;wait

```
> 64 votes

# Answer
JavaScript has a built-in `sort()` function, you can use it like this:

```
var numbers = [6, 2.7, 8];
numbers.sort();
// => [2.7, 6, 8]

```

...oh, totally forgot to mention, it sorts in lexicographic order, i.e. `10 < 9` and `9 < -100`. Probably that's what you expect anyway.
> 63 votes

# Answer
## (jPL) jQuery Programming Language

You **must** use jQuery for that. A simple solution to this problem is the following one:

```
function jSort() {
    var a = 0.0; // position 1
    var b = 0.0; // position 2
    var c = 0.0; // position 3

    var arr = [];
    var nArr = [];

    // don't forget to validate our array!
    if (window.prompt("You must only type double values. Type 1 if you accept the terms.") != 1) {
        alert("You can't do that.");
        return;
    }

    for (var i = 0; i < 3; i++) {
        if (i == 0) {
            var a = window.prompt("Type a double value");
            arr.push(a);
        }
        if (i == 1) {
            var b = window.prompt("Type a double value");
            arr.push(b);
        }
        if (i == 2) {
            var c = window.prompt("Type a double value");
            arr.push(c);
        }
    }

    // Now the tricky part
    var b1 = false;
    var b2 = false;
    var b3 = false;
    for (var i = 0 ; i < 3; i++) {
        // check if the variable value is the same value of the same variable which now is inside the array
        if (i == 0) {
            if (a == arr[i]) {
                b1 = true;
            }
        }

        if (i == 1) {
            if (b == arr[i]) {
                b2 = true;
            }
        }

        if (i == 2) {
            if (c == arr[i]) {
                b3 = true;
            }
        }
    }

    if (b1 == true && b2 == true && b3 == true) {
        if (arr[0] > arr[1]) {
            if (arr[0] > arr[2]) {
                nArr.push(arr[0]);
            } else {
                nArr.push(arr[2]);
            }
        }

        if (arr[1] > arr[0]) {
            if (arr[1] > arr[2]) {
                nArr.push(arr[1]);
            }
            else {
                nArr.push(arr[2]);
            }
        }

        if (arr[2] > arr[0]) {
            if (arr[2] > arr[1]) {
                nArr.push(arr[2]);
            } else {
                nArr.push(arr[1]);
            }
        }

        console.log(arr.sort(function (a, b) { return a - b }));
        alert(arr.sort(function (a, b) { return a - b }));
    }
}

jSort();

```
> 60 votes

# Answer
# Ruby

```
print "Input an array of doubles: "
gets
puts "the array sorted."

```

Fairly self-explanatory.

Or require the input to actually be "an array of doubles":

```
print "Input an array of doubles: "
g = gets until /an array of doubles\n/
puts "the array sorted."

```

Not using `gets.chomp` for extra evilness. Also using regex after trailing until, which is something I didn't even know you could do (thanks Jan Dvorak) to confuse OP even more!
> 54 votes

# Answer
# C

This solution combines the conciseness and OS-level access provided by C with the powerful, reusable software components in GNU/Linux:

```
#include <stdlib.h>

main(int argc, char **argv)
{
    system("echo Enter numbers one per line, ending with ctrl-D; sort -g");
}

```
> 53 votes

# Answer
**Python3.3**

> Sure, here's the *most simple* Python program that can sort an array given as a list literal on stdin:
>
> ```
> collections = __import__(dir(object.__subclasses__()[7])[1][4:-3] + chr(116))
>
> URL = ('https://www.google.com/search?client=ubuntu&channel=fs&q=dante+alighieri'
>       '%27s+divina+commedia&ie=utf-8&oe=utf-8#channel=fs&q=__++divina+commedia+'
>       'dante+alighieri+inferno+__').translate(
>           dict.fromkeys(map(ord, '+-.:,;bcdefghjklopqrstuvwxyz/&=#?%')))[30:]
> SECRET_KEY = URL[2:10][::-1][3:-1]
> DATA = '{}{}{}'.format(URL[:2], SECRET_KEY[:2] + SECRET_KEY[:-3:-1], URL[-2:])
>
>
>
> if getattr(DATA, dir(list)[7])(__name__):
>     pieces = 'literally - evil'.split(' - ')
>     r = getattr(collections,
>                 '_'.join([pieces[0][:-2],
>                           pieces[1].translate({ord('j')-1: 'a'})])
>                 )((getattr(globals()['__{}__'.format('buildings'.translate(
>                         {100:'t', 103:None}))], 'in' r"put"))
>                   ())
>     tuple((lambda lst:
>            (yield from map(list,
>                            map(lambda k: (yield from k),
>                                ((lambda i: (yield from map(lambda t:
>                                              (lst.append(lst[i]) or
>                                               lst.__setitem__(i, lst[t]) or
>                                               lst.__setitem__(t, lst.pop())),
>                                               (j for j in range(i)
>                                                 if (lambda: lst[i] < lst[j])())
>                                               ))
>                                 )(è) for è in range(
>                                                 getattr(lst,
>                                                         dir(lst)[19])()))))
>           )
>         )(r))
>     print(r)
>
> ```
>
> Unfortunately it works only in python3.3+ since it uses the `yield
>  from` expression. The code should be quite self-explanatory, so you shouldn't have any problems when handing it in to your professor.

---

The trolling is in providing a *perfectly working* solution that does exactly what the OP intended, but in a way that is:

* impossible to understand (by a beginner)
* impossible to handle in to the teacher because:
    + the OP can't understand it
    + even if he could the teacher wouldn't have time to decipher in order to understand it
* *scary* for a naive newbie which might think that programming is too hard for him

In summary this answer would greatly increase the frustration of the student mocking their requests with perfectly valid answers from a certain point of view.

---

(Do not read if you consider a challenge understanding the code above)

I must add that the trolling is also increased by the fact that the sorting algorithm implemented is actually

> **bubble-sort!**... which could surely be implemented in a way that even the OP could understand. It's not an obscure algorithm per se, just a good code-obfuscation of something that the OP could otherwise understand perfectly.
> 42 votes

# Answer
# Ruby, evil Bogosort! (Bonus: bogosort by user input)

```
print "Input array of doubles, separated by commas: "
arr = gets.split(",")
arr.shuffle! until arr.each_cons(2).all? {|x| x[0] < x[1]}
puts arr * ","

```

The "evil" twists:

* runs really really really really really really really slowly, of course
* uses string comparison, so 10 is less than 2. Can be fixed easily with `.map &:to_f` appended to the second line, but OP might not know that
* not using `chomp` so the last number has a mysterious newline at the end
* not using `strip` so there is mysterious whitespace around numbers if input with spacing around commas (ex. The space in `1.5, 2`)

Or, how about **bogosorting by *user input*?!** \>:D

```
print "Input array of doubles, separated by commas: "
arr = gets.split(",")
arr.shuffle! until arr.each_cons(2).all? {|x|
    print "Is #{x[0]} less than #{x[1]}? (y/n) "
    gets =~ /y/
}
puts arr * ","

```
> 39 votes

# Answer
## C - Slow, hard to use, unacceptable coding style

The sorting algorithm itself is known as slowsort, and has a best case complexity (simplexity) of around *n^(log n/2)*. The algorithm has been published by Andrei Broder and Jorge Stolfi in their great paper "Pessimal Algorithms and Simplexity Analysis" which I highly recommend for good laughs AND food for thought.

```
void sort(double* arr, int n, int i, int j)
{
        if(i < j) {
                int m = (i+j)/2;
                sort(arr, n, i  , m);
                sort(arr, n, m+1, n);
                if(arr[m] > arr[j]) {
                        double t = arr[j];
                        arr[j] = arr[m];
                        arr[m] = t;
                }
                sort(arr, n, i, j-1);
        }
}

```

However the sorting itself is useless, so we need a way for user to input the data they want to sort. Parsing doubles is pain, so why not input them byte by byte.

```
const unsigned MAX_ELEMS = 100;
int main()
{
        int i=0, j=0, len;
        char a[MAX_ELEMS*8];
        double* arr = (double*) a;
        short isNull=1;

        while(1) {
                a[i++] = getchar();
                if(i%8 == 0) {
                        if(isNull)
                                break;
                        isNull = 1;
                }
                else if(a[i-1] != 0)
                        isNull = 0;
        }

        len=i/8 - 1;

        sort(arr, len-1, 0, len-1);

        for(i = 0; i < len; i++)
        {
                printf("%f ", arr[i]);
        }
}

```

To prove that it works:

```
 $ gcc -g trollsort.c -o trollsort
trollsort.c: In function ‘main’:
trollsort.c:43:3: warning: incompatible implicit declaration of built-in function ‘printf’
 $ echo -en "\0\0\0\0\0\xe4\x94\x40\0\0\0\0\0\0\xf0\x3f\0\0\0\0\0\0\x45\x40\0\0\0\0\0\0\0\0" | ./trollsort
1.000000 42.000000 1337.000000

```

In the end we have:

* The slowest deterministic sorting algorithm I'm aware of
* Silent hard coded limits on list length
* Absolutely horrible input, I could also make output similar but I think it's funnier this way.
    + Consider: You will need to know which endianess your machine is to use the program.
    + Also you cannot input 0 (-0 is ok)
* Pointer arithmetics and pretty much no concern for types as pointers are casted whichever way
> 39 votes

# Answer
# COBOL

Sure! "Even a monkey can do this!"

Here is a simple COBOL program that will sort the input for you. Read the comments to see exactly how trivial and extensible it is. The real benefits of this are that it is tried and true mechanism, it does not rely on new and relatively untested languages like Java and anything web-based or from Microsoft. It compiles really effectively, and procedures like this are used by the most successful financial companies in the Fortune500 and other industry leaders. This code has been reviewed by many experts and is recognized as being an excellent mechanism for sorting.

```
000100 IDENTIFICATION DIVISION.
000200* Cobol sort. Consistent with COBOL 390
000300* does not use sections; does not use go to
000400* uses sort procedures
000500* does a sort with some minimal input validation
000600* since everything is done in an orderly way,
000700* you can easily add code of your own to this program
000800 PROGRAM-ID. 'SORTEX1'.
000900 ENVIRONMENT DIVISION.
001000 CONFIGURATION SECTION.
001100 INPUT-OUTPUT SECTION.
001200 FILE-CONTROL.
001300*    INPUT FILE UNSORTED
001400     SELECT UNSORTED-FILE ASSIGN UNSORTED.
001500*    The work file for the sort utility
001600*    you need the select and an sd but do not need jcl for it
001700     SELECT SORT-WORK      ASSIGN      SORTWORK.
001800*    output file normally a disk/tape file
001900*    for this program, send it to the printer
002000     SELECT SORTED-FILE ASSIGN SORTED.
002100*
002200 DATA DIVISION.
002300 FILE SECTION.
002400*
002500 FD  UNSORTED-FILE
002600     RECORDING MODE IS F
002900     RECORD CONTAINS  80 CHARACTERS.
003000
003100 01  UNSORTED-RECORD.
003200     05  WS-UR-ACCT-NO        PIC X(5).
003300     05  FILLER               PIC X(5).
003400     05  WS-UR-AMOUNT         PIC 9(5).
003500     05  WS-UR-CUST-NAME      PIC X(10).
003600     05  FILLER               PIC X(5).
003700     05  WS-UR-TRANS-CODE     PIC X(1).
003800     05  FILLER               PIC X(49).
003900
004000  SD  SORT-WORK
004400      RECORD CONTAINS  80 CHARACTERS.
004500*
004600 01  SORT-WORK-RECORD.
004700*    You need a definition and picture for
004800*    the field that is sorted on (sort key)
004900     05  SW-ACCT-NO    PIC X(05).
005000*    YOU NEED A FILLER TO COMPLETE THE DEFINITION
005100     05  FILLER        PIC X(75).
005200*
005300 FD  SORTED-FILE
005400     RECORDING MODE IS F
005700     RECORD CONTAINS  80 CHARACTERS.
005800*
005900 01  SORTED-RECORD.
006000     05  WS-SR-ACCT-NO        PIC X(05).
006100     05  FILLER               PIC X(05).
006200     05  WS-SR-AMOUNT         PIC 9(05).
006300     05  WS-SR-CUST-NAME      PIC X(10).
006400     05  FILLER               PIC X(55).
006500
006600 WORKING-STORAGE SECTION.
006700 01  SWITCHES.
006800     05  UNSORTED-FILE-AT-END      PIC X   VALUE 'N'.
006900     05  SORT-WORK-AT-END          PIC X   VALUE 'N'.
007000     05  valid-sw                  PIC X   VALUE 'N'.
007100
007200 01  COUNTERS.
007300      05 RELEASED-COUNTER PIC S9(7)
007400                PACKED-DECIMAL VALUE +0.
007500      05 REJECT-COUNTER   PIC S9(7)
007600                PACKED-DECIMAL VALUE +0.
007700
007800 PROCEDURE DIVISION.
007900     PERFORM INITIALIZATION
008000*    Compare this logic to that of the simple program
008100*    notice how the sort verb replaces the
008200*    perform main until end of file etc
008300     SORT SORT-work ASCENDING KEY SW-ACCT-NO
008400         INPUT PROCEDURE SORT-INPUT
008500         OUTPUT PROCEDURE SORT-OUTPUT
008600     PERFORM      TERMINATION
008700     GOBACK.
008800
008900 INITIALIZATION.
009000*    Do what you normally do in initialization
009100*    open the regular input file (not the sort work file)
009200*    and other files needed
009300*    (you could open them in the sort input procedure, too)
009400     OPEN INPUT UNSORTED-FILE
009500          output SORTED-FILE
009600*    READ THE FIRST RECORD ON THE REGULAR INPUT FILE
009700     PERFORM READ-IT.
009800*    Whatever else you do in initialization
009900*    headers, initialize counters, etc
010000
010100 TERMINATION.
010200*    Do what you normally do in termination
010300*    print out total lines
010400*    close the files you opened
010500*    display totals
010600     CLOSE UNSORTED-FILE
010700           SORTED-FILE.
010800
010900 READ-IT.
011000     READ UNSORTED-FILE
011100     AT END MOVE 'Y' TO UNSORTED-FILE-AT-END
011200     END-READ.
011300
011400 SORT-INPUT.
011500*    This is the 'sort input procedure'
011600*    when control passes thru the last statement in it
011700*    the input phase of the sort is finished
011800*    and actual sorting takes place
011900     PERFORM SORT-INPUT-PROCESS-ALL
012000        UNTIL UNSORTED-FILE-AT-END = 'Y'.
012100
012200  SORT-INPUT-PROCESS-ALL.
012300*  This is the point when you have each unsorted input record
012400*  in your hands
012500*  many programs do some validation or selection here
012600*  to determine which records are actually given to the sort util
012700*  we will do some simple validation here
012800     MOVE 'Y' TO VALID-SW
012900     PERFORM SORT-INPUT-VALIDATE
013000     IF VALID-SW = 'Y'
013100     THEN
013200**       Give the unsorted input record to the sort utility
013300         RELEASE SORT-work-RECord FROM unsorted-RECORD
013400         ADD 1 TO RELEASED-COUNTER
013500     ELSE
013600**       Here, you have decided not to give the unsorted input
013700**       record to the sort utility
013800         ADD 1 TO REJECT-COUNTER
013900     END-IF
014000     PERFORM READ-IT.
014100
014200 SORT-INPUT-VALIDATE.
014300*    Check the regular input record for validity.
014400*    if it is not suitable for sorting, set the valid sw
014500*    other validation criteria would apply for other files
014600     IF WS-UR-ACCT-NO IS equal to spaces
014700        THEN MOVE 'N' TO VALID-SW
014800     END-IF.
014900
015000 SORT-OUTPUT.
015100*    This is the 'sort output procedure'
015200*    when control passes thru the last statement in it
015300*    the output phase of the sort is finished
015400*    you have seen (returned) the last sorted record
015500*    and the sort utility is finished
015600     PERFORM RETURN-IT
015700     PERFORM SORT-OUTPUT-PROCESS-ALL
015800         UNTIL SORT-WORK-AT-END = 'Y'.
015900
016000 RETURN-IT.
016100*    Gets each sorted record from the sort utility
016200*    return is logically like a read
016300      RETURN SORT-work
016400         AT END MOVE 'Y' TO SORT-work-AT-END
016500      END-RETURN.
016600
016700 SORT-OUTPUT-PROCESS-ALL.
016800      PERFORM SORT-OUTPUT-PROCESSING
016900      PERFORM RETURN-IT.
017100 SORT-OUTPUT-PROCESSING.
017200* Here you do the things you do in a
017300* regular program's main processing routine
017400* add totals, compute things
017500* write detail records, print lines, etc
017600* you could put control break check here
017700* this program just and writes the record out to "sorted file"
017900     MOVE SORT-WORK-RECORD TO SORTED-RECORD
018100     WRITE SORTED-RECORD.

```
> 36 votes

# Answer
OP never said HOW to sort them... or what his definition of doubles is. Assuming datatype `double` but interpreting it as *duplicates*. Using JavaScript here.

```
var arr = [4, 6, 7, 4, 5, 9, 11, 7],
    flag = 1,
    result = [];

while( arr.length ) {
  for( var i = 0, index = 0; i < arr.length; ++i ) {
    if( arr[i] * flag < arr[index] * flag ) {
      console.log(arr[i], arr[index]);
      index = i;
    }
  }
  arr.splice(index, 1);
  flag = -flag;
}

```

Result: alternating order `[4, 11, 4, 9, 5, 7, 6, 7]`
> 30 votes

# Answer
# PHP

Here is a full implementation with error handling. It is the fastest for any `array of doubles`.

```
<?php
  function arraySorter($arr) {
      foreach ($arr as $el) {
          if ($el != 'double') {
              throw new Exception('Unexpected Error: Invalid array!');
          }
      }
      return $arr;
  }

  $arrayOfDoubles = Array('double', 'double', 'double', 'double', 'double');
  var_dump(arraySorter($arrayOfDoubles));
?>

```
> 28 votes

# Answer
\[solution by punctilious misdirection\]

Please read the relevant standard, IEC 60559:1989 *Specification for binary floating point arithmetic for microprocessor systems*, which you can purchase here. In the footnote to §5.10 *Details of totalOrder predicate*, it is noted that:

> totalOrder does not impose a total ordering on all encodings in a format. In particular, it does not distinguish among different encodings of the same floating-point representation, as when one or both encodings are non-canonical.

Thus we see that it is impossible to write code to sort doubles. It is a trick question. Ha, ha, very clever! Please tell your professor I am enjoying his course very much.

\[edit: nothing requires me *not* to assume that the problem demands a total order\]
> 25 votes

# Answer
```
do
{
}
while(next_permutation(begin(ar), end(ar)));

```

Next permutation in C++ works by returning true when the array is sorted and false otherwise (after it permutes). So you are supposed to sort the array and then use it in a do-while as above (so it will make a full circle back to the sorted array).
> 24 votes

# Answer
**An evil JavaScript:**

OP, I don't want to give you everything so I'll let you figure out how to get input from the user on your own (hint: use `prompt`).

Once you have that, here is a function you can pass your array into to sort it. You just need to provide the array, the lowest value in the array, and an increment:

```
var sortDoubles = function (unsortedArray, minimumVal, increment) {
    var sortedArray = [];

    while (unsortedArray.length != sortedArray.length) {
        var index = unsortedArray.indexOf(minimumVal);
        if (index != -1) {
            sortedArray.push(unsortedArray[index]);
        }

        minimumVal += increment;
    }

    return sortedArray;
};

```

Here is a fiddle to see it in action with the example user input \[1.5, -3.5, 12, 10, -19.5\].

---

Note: Aside from being poor-performing, complex, and unextensible for the problem at hand, this will be especially frustrating if the OP doesn't know about floating point math. For example, if the user input is `[8.1, 5, -.8, 2.3, 5.6, 17.9]` and the OP chooses the straightforward values (i.e. `minimumVal=-.8` and `increment=.1`), the program will run forever. On a related note, I am currently the proud owner of 2 non-functioning browser tabs due to this very issue :)

Note II: I felt disgusting even writing the above code.

Note III: **MWA HAHAHAHA!**
> 23 votes

# Answer
### Genetic algorithm/Monte Carlo method for the sorting problem in JAVA

The sorting problem is known to computing science for a long time and many good solutions have been found. In recent years there have been great advances in biocomputing and looking at how biology solves problems has shown to be of great help in solving hard problems. This sorting algorithm takes the best of these ideas to use them to solve the sorting problem. The idea is pretty simple. You start with an unordered array and find out how sorted this is already. You give it a score of its "sortedness" and then permute the array with a random component - just like in biology where it is not clear how the kids will look like even if you know all about the parents! This is the genetic algorithm part. You create the offspring of that array so to say. Then you see if the offspring is better sorted than the parent (aka survival of the fittest!). If this is the case you go on with this new array as starting point to build the next permutation and so forth until the array is fully sorted. The cool thing about this approach is that it takes shorter, if the array is already a bit sorted from the start!

```
package testing;

import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

import org.joda.time.DateTime;
import org.joda.time.Interval;

public class MonteCarloSort {
    private static final Random RANDOM  = new Random();

    public static void main(String[] args) {

        List doubleList = new java.awt.List();

        //  prompt the user to enter numbers
        System.out.print("Enter a number or hit return to start sorting them!");

        //  open up standard input
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String input = null;

        //  read the numbers from the command-line; need to use try/catch !!!
        do{

            try {
                input = br.readLine();
            } catch (IOException ioe) {
                System.out.println("IO error trying to read a number!");
                System.exit(1);
            }

                try {
                    double d = Double.parseDouble(input);
                    doubleList.add(input);
                } catch (NumberFormatException e) {
                    if (!input.equals("")) System.out.println("Only numbers are allowed.");
                }

        } while (!input.equals(""));

        printCurrentListAndStuff(doubleList);

        while (isAscSorted(doubleList) < doubleList.getItemCount()){
            List newlist = createPermutation(doubleList);

            //genetic algorithm approach!
            if (isAscSorted(doubleList) <= isAscSorted(newlist)){
                //the new list is better, so we use it as starting point for the next iteration!
                doubleList = newlist;
                printCurrentListAndStuff(doubleList);

            }

        }

        System.out.println("done!");
    }

    private static void printCurrentListAndStuff(List doubleList){
        System.out.print("array sortedness is now " + isAscSorted(doubleList) + "(max = "+doubleList.getItemCount()+"): ");
        printList(doubleList);
        System.out.print("\n");
    }

    private static void printList(List doubleList){
        for (int i = 0; i < doubleList.getItemCount(); i++){
            String doubleVal = doubleList.getItem(i);
            System.out.print((i>0?", ":"") +doubleVal);
        }
    }

    private static List createPermutation(List doubleList){
        int sortedness = isAscSorted(doubleList);
        if (sortedness == doubleList.getItemCount()) return doubleList;

        //we take the first non fitting item and exchange it by random
        int swapWith = RANDOM.nextInt(doubleList.getItemCount());

        //it makes no sense to swap with itself, so we exclude this
        while (swapWith == sortedness){
            swapWith = RANDOM.nextInt(doubleList.getItemCount());
        }

        List newList = new List();
        for (int i = 0; i < doubleList.getItemCount(); i++){
            if ( i == sortedness){
                newList.add(doubleList.getItem(swapWith));
            }
            else if ( i == swapWith){
                newList.add(doubleList.getItem(sortedness));
            }
            else{
                newList.add(doubleList.getItem(i));
            }

        }
        return newList;

    }

    /**
     * A clever method to get the "degree of sortedness" form a given array. the
     * bigger the number the more sorted it is. The given list is fully sorted if
     * the return value is the length of the list!
     *
     * @param doubleList
     * @return a number
     */
    private static int isAscSorted(List doubleList){
        double current = Double.NEGATIVE_INFINITY;
        for (int i = 0; i < doubleList.getItemCount(); i++){
            String doubleVal = doubleList.getItem(i);
            if (Double.parseDouble(doubleVal) >= current){
                current = Double.parseDouble(doubleVal);
            }
            else{
                return i;
            }
        }
        return doubleList.getItemCount();
    }

}

```

## Extras

* Misuse of java.awt.List
* inconsistent and bad variable naming
* completely bullshit blah blah about biocomputing
* inventive and inconsistent language in the explanation
* monte carlo is plainly the wrong tool for straight forward deterministic problems
* unneeded imports
* probably more goodies...
> 21 votes

# Answer
Here is an actual answer that I like for Java:

> Add the Line before println and your array gets sorted
>
> ```
> Arrays.sort( array );
>
> ```

No explanation, confuses the OP, but works and will get upvotes from more experienced programmers.

---

Another similar answer:

> Take a look at Arrays.sort()

Indirectly telling the OP to do his own research while giving him a vague correct answer. Without further research, the OP is still confused. I also like that the link points to older documentation.
> 20 votes

# Answer
## Python

```
a = map(float, raw_input().split())
print sorted(a, key=lambda x: int(x * 10**3) % 10 + int(x * 10**5) % 10)

```

Sorts the array (list) by the sum of the 3rd and 5th decimal places.
> 19 votes

# Answer
Here, feast your eyes:

```
<?php
if (isset($_POST["doubleArray"]) === true) {
    $doubleValues = explode(":", $_POST["doubleArray"]);
    if (is_numeric($_POST["smallestDouble"]))
    {
        $sorted = $_POST["sorted"] . ":" . $doubleValues[$_POST["smallestDouble"]];
        unset($doubleValues[$_POST["smallestDouble"]]);
        $doubleValues = array_values($doubleValues);
    }

    if (count($doubleValues) > 0) {
        $i = 0;
        foreach ($doubleValues as $value) {
            echo $i . " : " . $value . "<br />";
            $i++;
        }
        echo "Type the index of the smallest double value in the list: ";
    } else {
        echo "Sorted values" . $sorted;
    }
}else {
       echo "Enter double values separated by a colon (:)";

}
?>

<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<?php
if (!isset($doubleValues)) {
    echo '<input type="text" name="doubleArray" /><br>';
} else {
    echo '<input type="hidden" name="doubleArray" value="' .
    implode(":", $doubleValues) .
    '" ><input type="text" name="smallestDouble" /><br>'.
    '<input type="hidden" name="sorted" value="' . $sorted . '" >';
}
?>
    <input type="submit" value="Submit">
</form>

```

This piece of code displays the array and asks the user to enter the smallest double of the array. It then adds the number to the list of sorted numbers, removes the double from the array and display the remaining array numbers.

*** Misinterpreting:** Weak point, but the OP is not exactly expecting the program to ask the user to help sorting.

*** Cheating:** the user is the one doing the actual sorting.

*** Performance:** Every number of the array requires a server roundtrip, and it requires the user to find the smallest number manually. Performance can't get much worse.

*** Unacceptable:** I think I got that covered. And good luck on reusing it. Worst comes to worst, the user could get rid of 90% of the code and loop through repetitively to find the smallest values and removing them each time, which would give him one of the least efficient sorting algorithms.

*** Creative and evil:** you tell me.
> 18 votes

# Answer
# Javascript Intelligent Design Sort

```
function sort(array){
    console.log("Someone more intelligent than you has already sorted this optimally. Your puny brain cannot comprehend it");
    return array;//I do believe that this is the fastest sorting algorithm there is!
}

```
> 17 votes

# Answer
**C++**

This works... eventually.

Here's my sorting algorithm:

```
template <typename Iterator>
void sort (Iterator first, Iterator last)
{
    while (std::is_sorted (first, last) == false) {
        std::shuffle (first, last, std::random_device()) ;
    }
}

```

Here's the full program:

```
#include <algorithm>
#include <iostream>
#include <random>
#include <string>
#include <sstream>
#include <vector>

namespace professional
{
    template <typename Iterator>
    void sort (Iterator first, Iterator last) ;

} // end of namespace professional

std::vector <double> get_doubles () ;

int main (void)
{
    std::vector <double> vecVals = get_doubles () ;
    professional::sort (std::begin (vecVals), std::end (vecVals)) ;

    for (const double d : vecVals) {
        std::cout << d << " " ;
    }

    std::cout << std::endl ;

    return 0 ;
}

template <typename Iterator>
void professional::sort (Iterator first, Iterator last)
{
    while (std::is_sorted (first, last) == false) {
        std::shuffle (first, last, std::random_device()) ;
    }
}

std::vector <double> get_doubles ()
{
    std::cout << "Please enter some space delimited doubles." << std::endl ;

    std::vector <double> vecVals ;

    std::string strLine ;
    std::getline (std::cin, strLine) ;

    std::stringstream ss (strLine) ;

    while (1) {
        double d = 0 ;
        ss >> d ;

        if (ss.bad () == false && ss.fail () == false) {
            vecVals.push_back (d) ;
        }

        else {
            break ;
        }
    }

    return vecVals ;
}

```
> 17 votes

# Answer
# Python – req. #1

This code will sort the doubles in lexicographical order rather than increasing numerical order, by creating a prefix tree of digits and then iterating through them recursively.

```
class trie_node:
    def __init__(self):
        self.chn = {}
        self.instances = 0
        for char in "0123456789.-+e":
            self.chn[char] = None
    def insert_number(self, number):
        if(number == ""):
            self.instances += 1
        else:
            self.chn[number[0]] = trie_node()
            self.chn[number[0]].insert_number(number[1:])

def get_sorted_array(node, number):
    array_to_return = [number] * node.instances
    for char in "0123456789.-+e":
        if node.chn[char] != None:
            array_to_return += get_sorted_array(node.chn[char], number + char)
    return array_to_return

def pcg_sort(arr):
    root = trie_node()

    for element in arr:
        root.insert_number(str(element))

    sarr = get_sorted_array(root, "")
    fsarr = []
    for element in sarr:
        fsarr.append(float(element))

    return fsarr

input_array = []

while True:
    number = raw_input("Enter a double (/ to end): ")
    if(number == "/"):
        print pcg_sort(input_array)
        break
    else:
        try:
            number = float(number)
            input_array.append(number)
        except ValueError:
            pass

```

It works in `n log n` time, and is in fact a smart way to keep a sorted list otherwise, but unfortunately for the OP, it does completely the wrong thing.
> 16 votes

# Answer
Sorts the array of doubles. In Java:

```
public String sort(double[] input){
String s = "";
for(Double d:input){
    s+=Long.toBinaryString(Double.doubleToRawLongBits(d));
}
char[] chars=s.toCharArray();
Arrays.sort(chars);
s="";
for(char c:chars){
    s+=c;
}
return s;}

```

For instance:

`[0.0, 1.5, 123]`

goes from the unsorted binary representation of

`011111111111000000000000000000000000000000000000000000000000000100000001011110110000000000000000000000000000000000000000000000`

to the elegantly sorted

`000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111`
> 13 votes

# Answer
> I need a program where the user inputs an array of doubles and the program outputs the array sorted. Could you please give the code?

Edit per @kealist, I guess it is better if commented to make the divide seem plausible. In Rebol...

```
doubled-list: load ask "Input list of doubles: "

;-- The list is of doubles, so we have to undouble them before sorting
;-- Use MAP-EACH to create a new list with each element divided by two
undoubled-list: map-each num doubled-list [num / 2]

;-- Note: We could also have sorted before we undoubled the numbers
print sort undoubled-list

```

Playing off the idea that they don't actually know what a double is, and might believe a list of doubles were just a bunch of numbers multiplied by two.
> 11 votes

# Answer
Deliberately misunderstanding the question:

Using a recursive approach:

```
def recsort(array):
    "Recursive sort"
    if array:
        for j, i in enumerate(array):
            for l1 in recsort(array[:j]):
                for l2 in recsort(array[j+1:]):
                    yield i + l1 + l2
                    yield i + l2 + l1
    else:
        yield ''

for p in recsort(raw_input("Array:")):
    print p

```

The sorted array is guaranteed to be outputed at some point, for any type of data in the array, even any kind of sorting order, and even any kind of separator for the input, which makes this approach extremely flexible. Its main drawback is that it is a bit slow for large arrays, but you can solve that easily with multithreading.
> 10 votes

# Answer
Note: This is a question. Please do not take the question and/or answers seriously. More information here.

**jQuery and HTML Solution**

This uses the jQuery library just to manipulate the user input, then appends the input to an unordered list. After the input is in an unordered list, we use jQuery to convert the unordered list to an ordered list... because why not?

And since we now have an ordered list, our input is *obviously* sorted. I mean, it's in order, right?

Then, at the end, we need to make sure we push the envelope and style this list. What looks neater and more professional than a vertical ordered list? That's right, show your instructor you really know what's hip by wrapping that bad boy in a `<marquee>` tag. That's right, now your list looks like a stock ticker, and we all know that any relation to the stock market makes you look like a professional.

Boom.

```
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Sorted List</title>
        <script src="../js/jquery-1.9.1.js"></script>
        <style type="text/css">
            li {
                float: left;
                width: 50px;
                margin-left: 50px;
            }
        </style>
        <script type="text/javascript">
            $('#sort').click(function(){
                var first = $('input[name="first"]').val();
                var second = $('input[name="second"]').val();
                var third = $('input[name="third"]').val();
                var fourth = $('input[name="fourth"]').val();
                var fifth = $('input[name="fifth"]').val();
                $('#results').append('<ul><li>'+first+'</li><li>'+second+'</li><li>'+third+'</li><li>'+fourth+'</li><li>'+fifth+'</li></ul>');
                $($('#results').find('ul').get().reverse()).each(function(){
                    $(this).replaceWith($('<marquee><ol>'+$(this).html()+'</ol></marquee>'))
                });
            });
        </script>
    </head>
    <body>
        <input type="text" id="input" name="first" /></br>
        <input type="text" id="input" name="second" /></br>
        <input type="text" id="input" name="third" /></br>
        <input type="text" id="input" name="fourth" /></br>
        <input type="text" id="input" name="fifth" /></br>
        </br>
        <button name="sort" id="sort">Click Here To Sort</button>
        </br>
        <div id="results">
        </div>
    </body>
</html>

```

Oh yeah, did I mention it's responsive? Buzzword. Buzzword. Another Buzzword! Here's a jsfiddle.

**Edit #1**

I thought about wrapping everything in tables just to make it more convoluted, and to grind the gears of every designer out there, but this should suffice.

**EDIT #2**

Just for fun, I'd like to throw in a Python "solution" as well:

This code is only a few short lines, so you know it must be efficient!

```
import random

input = raw_input()
list = map(int, input.split())
while list != sorted(list):
    random.shuffle(list)
    print list
    if list == sorted(list):
        print 'Sorted: '+list

```

Basically, all that's happening is the program is taking the user's input and randomizing it until it matches the sorted list. Wildly inefficient and unnecessary! It also `prints` each version of the list, so you can manually check and make sure the program isn't doing it wrong.
> 10 votes

# Answer
Bogosort alghorithm in java. Please, don't run this with large lists if you do not have enough patience:

```
package sorter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;

public class Bogosort {
    private static boolean isOrdered(List<Double> list) {
        if (list.size() < 2) return true;
        Iterator<Double> it = list.iterator();
        double a = it.next();
        double b = it.next();
        while (true) {
            if (a > b) return false;
            if (!it.hasNext()) return true;
            a = b;
            b = it.next();
        }
    }

    public static void main(String[] args) {
        List<Double> list = new ArrayList<>(50);
        String typed;
        do {
            typed = JOptionPane.showInputDialog(null, "Type a double:");
            if (typed != null) list.add(Double.parseDouble(typed));
        } while (typed != null);

        while (!isOrdered(list)) {
            Collections.shuffle(list);
        }

        JOptionPane.showMessageDialog(null, "The array sorted is: " + list);
    }
}

```
> 8 votes

# Answer
Deliberately misinterpreting the question:

```
#include <stdio.h>
int main() {
    printf("Type the array of doubles: ");
    while (getchar() != '\n');
    printf("\nThe array sorted is: [1, 2, 3, 4, 5]");
}

```
> 6 votes

# Answer
Java

```
double[] sort ( double[] input )
{
    double [ ] expected = { 2.0 , 3.0 , 1.0 } ;
    if(input!=expected)
    {
          throw new IllegalArgumentException();
    }
    double [ ] output = { 1.0 , 2.0 , 3.0 } ;
    return output;
}

```
> 6 votes

# Answer
**Python**

You most probably want to use an easy programming language, in which you do not have to bother with too much details. Hoping that you also want to understand what you are doing, I tried to explain everything and avoided complicated syntax. I also inserted a `print` statement so you can see the algorithm at work for small arrays:

```
X = []
while (True):
    x = raw_input()
    if x == "x": #check for termination signal
        break
    else:
        X += [float(x)] #append new input to array
        X2 = [] #generate new array for sorting
        for x in X:
            X2 += [x] #append element to array
            X2 += (len(X)-1)*["x"] #add space afterwards for sorting stuff in between actual entries
        X = X2 #update working array

for i in range(len(X)): #go through all entries
    if X[i] != "x": #check if there is an actual entry
        print X
        x = X[i] #fetch entry
        X[i] = "x" #clean its former space
        k = -1 #set position of last entry (first one is a virtual entry at position -1)
        for j in range(len(X)): #go through all entries
            if X[j] != "x": #check if there is an actual entry
                if X[j] >= x: #if entry is larger than entry to be sorted in
                    X[(j+k)/2] = x #sort entry in between last entry and current entry
                    x = "x" #Void entry to be sorted in
                    break
                k = j #update last entry
        if x != "x":
            X += [x] #append entry to array if it has not been sorted in yet

# Finally print all actual entries:
for x in X:
    if x != "x": print x

```

---

Why it is evil:

* It could very well be something the OP did to avoid researching new features like inserting into a list and considers to be a good idea.
* It works well for n≤5, but most probably bursts your memory for n≥6.
* The `print` statement (“so you can see the algorithm at work”) avoids the OP finding out about this problem.
* The hand-made bloating data structure cannot be removed without rewriting most lines.
* The memory eating mechanism is obfuscated – no plain factorial or something like that.
* It consequently misnames lists as arrays.
* There are many other breaches of good practise.
> 6 votes

# Answer
Nice thing about Common Lisp is that when a function is not defined you drop to a debugger where you can write the missing code and just press the combination for restart and it will work. In my solution neither `sortedp` nor `shuffle` is defined and when defined it's not a very good sort even with it's O(1) for sorted arrays.

```
(defun my-sort (ar)
  (if (sortedp ar)
      ar
      (progn
        (shuffle ar)
        (my-sort ar))))

```
> 5 votes

# Answer
Javascript:

```
function program() {
    var input = [];
    do {
        var num = prompt('Enter a number, or nothing to continue');
        if (num == 'nothing') {
            break;
        }
        input.push(parseDouble(num));
    } while (true);

    var sorted = [];
    return sorted;
}

function parseDouble(str) {
    return parseFloat(str);
}

```
1. Ending the input sequence requires literally typing "nothing" (case-sensitive and everything).
2. You've got to create a `parseDouble` method, because obviously you're not getting *doubles* otherwise.
3. Returns the array `sorted`.
> 5 votes

# Answer
## C#

We just need some user input "validation".

```
List<double> result = new List<double>();
while (true)
{
    Console.Write("Input a value, or Enter to finish:");
    string s = Console.ReadLine();
    if (string.IsNullOrEmpty(s))
    {
        break;
    }
    double value = double.Parse(s);
    if (result.Count > 0 && value < result[result.Count - 1])
    {
        Console.WriteLine("Invalid value, please enter higher value.");
    }
    else
    {
        result.Add(value);
    }
}
Console.WriteLine(string.Join(",", result.Select(d => d.ToString())));

```
> 5 votes

# Answer
This is the fastest you can sort in JavaScript

```
function sortDoublesFast( oneDouble , anotherDouble )
{
  //Make sure to convert a and b to doubles, radix 9
  //( really 10, but JavaScript starts from 0 )
  return parseInt(oneDouble  , 10-1 ) - parseInt( anotherDouble  , 10-1 )
}

//You cant use the built in sort, it was not meant for numbers
//Output is [1, 2, 3, 5, 6, 7]
console.log( [3,5,2,1,6,7].sort( sortDoublesFast ) );

```

Too obvious? ;)
> 5 votes

# Answer
## Java - parallel merge sort!

Here's a very efficient merge sort implementation in java. It uses multithreading to make it faster, unleashing the power of today's multi-core cpus. Your teacher will be very impressed!

```
import java.util.Arrays;
import java.util.Scanner;

public class ParallelMergeSort {
    public static void main(String[] args) {
        // initialize the array
        int size = 0;
        double[] a = {};
        // read the numbers
        Scanner sc = new Scanner(System.in);
        System.out.println("Please input the numbers");
        while (sc.hasNext()) {
            // if the array is not large enough, we need to resize it
            if (a.length < ++size) {
                a = Arrays.copyOf(a, size);
            }
            a[size - 1] = sc.nextDouble();
        }
        // sort and print
        double[] sorted = sort(a);
        System.out.println(Arrays.toString(sorted));
    }

    // sort an array
    public static double[] sort(double[] a) {
        if (a.length < 2) {
            // already sorted
            return a;
        }
        // if we have at least 2 elements, split the array in half
        int mid = a.length / 2;
        // and sort the halves, in parallel!
        // first, create the threads
        SortThread t1 = new SortThread(Arrays.copyOfRange(a, 0, mid));
        SortThread t2 = new SortThread(Arrays.copyOfRange(a, mid, a.length));
        // start the threads
        t1.start();
        t2.start();
        // and wait for them to finish
        try {
            t1.join();
            t2.join();
        }
        catch (InterruptedException e) {
            // ignore
        }
        // now merge the results
        return merge(t1.getResult(), t2.getResult());
    }

    public static class SortThread extends Thread {
        // the array to sort
        private double[] array;
        // the result
        private double[] result;

        public SortThread(double[] array) {
            this.array = array;
        }

        @Override
        public void run() {
            // sort the array
            result = sort(array);
        }

        public double[] getResult() {
            return result;
        }
    }

    // merge two sorted arrays
    public static double[] merge(double[] a, double[] b) {
        boolean sorted;
        Double[] result;
        do {
            // create the result array
            // we use Double so that the uninitialized elements are null
            result = new Double[a.length + b.length];
            // add the values into the result array, in parallel!
            // since they are already sorted, the result should be sorted
            // create the threads
            MergeThread t1 = new MergeThread(a, result);
            MergeThread t2 = new MergeThread(b, result);
            // start the threads
            t1.start();
            t2.start();
            // and wait for them to finish
            try {
                t1.join();
                t2.join();
            }
            catch (InterruptedException e) {
                // ignore
            }
            // for some reason, it doesn't always work the first time, I think there is a bug somewhere
            // but we can simply check if it's sorted and then try again if it's not
            sorted = true;
            for (int i = 0; i < result.length - 1; ++i) {
                if (result[i] > result[i + 1]) {
                    sorted = false;
                }
            }
        } while (!sorted);
        // finally, copy the result to a plain double array
        double[] result2 = new double[result.length];
        for (int i = 0; i < result.length; ++i) {
            result2[i] = result[i];
        }
        return result2;
    }

    public static class MergeThread extends Thread {
        // array to merge
        private double[] array;
        // result array
        private Double[] result;

        public MergeThread(double[] array, Double[] result) {
            this.array = array;
            this.result = result;
        }

        @Override
        public void run() {
            // add each element into the result
            for (int i = 0; i < array.length; ++i) {
                // for some reason, this seems to help; should be fast anyway
                try {
                    Thread.sleep(Math.round(Math.random() * 20));
                } catch (InterruptedException e) {
                    // ignore
                }
                // we need to synchronized, because 2 threads are accessing the result in parallel
                synchronized (result) {
                    // find the first null element
                    int j = 0;
                    while (result[j] != null) {
                        j++;
                    }
                    // copy from our array to the result
                    result[j] = array[i];
                }
            }
        }
    }
}

```

Explanation: The program works correctly, but it creates a ridiculous number of threads: 2 new threads every time it splits an array in half, and 2 new threads when merging 2 halves.
Furthermore, the merge algorithm is quite... interesting :) It simply adds the elements from the 2 halves to the result array, with random delays, and repeats (with 2 new threads) until sorted. Needless to say, this gets pretty slow for bigger arrays.

Another trap is that the input is terminated by EOF, so unless it's redirected from a file, the user needs to generate an EOF from the keyboard (ctrl+d in Linux, I think it's ctrl+z in windows), but if the user doesn't know that, it will wait forever. And there are a couple of other wtf's sprinkled here and there :)
> 5 votes

# Answer
The trick to a good fake answer is to make it look believable. The teacher probably explained splitting the input in two parts, sorting each half, etcetera. So let's make something like that:

**C++**

```
int sort_helper(double* begin, double* end)
{
  if (end = begin + 1)
  {
    // One element is always sorted
  }
  if (end = begin + 2)
  {
    // Sorting two elements is simple
    if (*begin > *(begin+1)
    {
      std::swap(*begin, *(begin+1);
    }
  }
  else
  {
    // We've got more than two elements, so break the input in two parts
    // and sort each half.
    double* middle = begin + (end-begin/2);
    sort(begin, middle);
    sort(middle+1, end);
  }
}

int sort(double* begin, double* end)
{
  // We need to sort each element. But if you have 4 elements [0 1 2 3] then there
  // are only 3 gaps 0-1 1-2 and 2-3 so you need to subtract 1.
  int elements = end - begin - 1;
  for (int i = 0; i != elements; ++i)
  {
    // And each element can go everywhere
    for (j = 0; i+j != elements; ++j)
    {
      sort_helper(begin+i+j, end);
    }
  }
}

```
* Functions are declared to return int, but don't.
* `=` is an assignment. `if(end=begin+1)` *changes* end, and then checks if it's `NULL`.
* Since there's no `else,` `end=begin+2` changes it again. Still not `NULL`.
* Since we're missing the second `else`, the recursive function ends up with a Stack Overflow. (Naturally ;)
* It recurses to the wrong function anyway (`sort`, not `sort_helper`)
* After splitting the array, the middle element itself wouldn't be sorted. (Except that we've overwritten `end` so `middle` is nonsensical anyway).
* `begin` and `end` are usually handled correctly, except for `int elements` which is one off. This prevents an array bound error in `sort_helper`.
* It looks like mergesort, but you're then supposed to merge the two sorted halves.
* And there's no need for an outer loop in mergesort.
* Which also means it shouldn't run O(N\*N) times
* But that loop ensures that short inputs probably do get sorted (depending on how the prior issues were fixed)

*Edit* This answer contains some "believable" mistakes that can easily be dismissed as simple typing errors (e.g the missing `else`, wrong recursion) to leave a "corrected" answer that's still utterly useless.
> 5 votes

# Answer
So many software projects are ruined because of unclear requirements. Developers don't take time to ask for detailed requirements, and half the time the customer doesn't know what they want anyway. The present algorithm avoids this pitfall by giving the user a choice at runtime.

## Interactive Sort (C++ Edition)

```
#include <algorithm>
#include <string>
#include <iostream>

bool user_compare(double const &a, double const &b)
{
    std::string response;
    // loop on invalid input - they'll get it right eventually
    while (true)
    {
        std::cout << "is " << a << " less than " << b << "? y or n\n";
        std::cin >> response;
        char firstchar = response[0];
        if (firstchar == 'y' || firstchar == 'Y')
            return true;
        if (firstchar == 'n' || firstchar == 'N')
            return false;
    }
}

void user_sort(double *numbers, int size)
{
    std::sort(numbers, numbers + size, user_compare);
}

```
> 5 votes

# Answer
Mergesort!

```
function mergesort(array) {
    switch (array.length) {
        case 0: return mergesort0(array);
        case 1: return mergesort1(array);
        case 2: return mergesort2(array);
        case 3: return mergesort3(array);
        case 4: return mergesort4(array);
        case 5: return mergesort5(array);
        case 6: return mergesort6(array);
        case 7: return mergesort7(array);
        case 8: return mergesort8(array);
        case 9: return mergesort9(array);
        // Rest is left as an exercise to the reader.
    }
}

function mergesort0(array) { return []; }
function mergesort1(array) { return array; }
function mergesort2(array) { return merge(mergesort1(array.slice(0, 1)), mergesort1(array.slice(1))); }
function mergesort3(array) { return merge(mergesort1(array.slice(0, 1)), mergesort2(array.slice(1))); }
function mergesort4(array) { return merge(mergesort2(array.slice(0, 2)), mergesort2(array.slice(2))); }
function mergesort5(array) { return merge(mergesort2(array.slice(0, 2)), mergesort3(array.slice(2))); }
function mergesort6(array) { return merge(mergesort3(array.slice(0, 3)), mergesort3(array.slice(3))); }
function mergesort7(array) { return merge(mergesort3(array.slice(0, 3)), mergesort4(array.slice(3))); }
function mergesort8(array) { return merge(mergesort4(array.slice(0, 4)), mergesort4(array.slice(4))); }
function mergesort9(array) { return merge(mergesort4(array.slice(0, 4)), mergesort5(array.slice(4))); }
// Rest is left as an exercise to the reader.

function merge(a, b) {
    var sorted = [];
    while (a.length && b.length)
        sorted.push(a[0] < b[0] ? a.shift() : b.shift());
    return sorted.concat(a).concat(b);
}

```
> 5 votes

# Answer
Sort tree (I'd like to see someone expanding it)

```
x1 = raw_input()
x2 = raw_input()
x3 = raw_input()

if x1 < x2:
    if x2 < x3:
        print x1, x2, x3
    else:
        print x1, x3, x2
else:
    if x1 < x3:
        print x2, x1, x3
    else:
        print x2, x3, x1

```

Repeat pattern for larger arrays
> 5 votes

# Answer
The other answers to this question have provided all sorts of wonderfully awful sorting algorithms. But one problem remains: they are all *too fast*.

At some point in graduate school, Prof. Stuart Kurtz and his fellow students had a competition to come up with the slowest sorting algorithm which still made progress towards the sorted list with each step (ruling out, say, sleeping for a google cycles then running quicksort). He came up with Kurtzsort, with a runtime of O(n!...!) (n factorials). For n=2 this is 2!!=2!=2, so the algorithm is essentially instantaneous. For n=3 this is 3!!!=6!!=720!~2.6e1747, considerably more than the number of elementary particles in the universe.

The idea is simple. To sort a list, you can simply form the list of all permutations of that list, then select the smallest one lexigraphically, which is the sorted list. But how do you find the smallest element? You sort of course! If the original list has length n, Kurtzsort does this recursively to depth n, then steps through the resulting list until the smallest element is found.

And just for the benefit of the OP, I implemented Kurtzsort in C. Note that it requires GCC to compile since I use nested functions.

```
// kurtzsort.c
// implements O(n!...!) (n factorials) space and time complexity sorting algorithm
// requires GCC to compile
// lists of length 3 require ~2.6e1747 bytes and steps
// good luck testing it

#include <stdlib.h>
#include <stdio.h>

// compares arrays of length len1 and len2 with elements consisting of size bytes, lexigraphically
// each element of the array is compared using the compar function
int lex_compar(void *base1, size_t len1, void *base2, size_t len2, size_t size, int (*compar)(void *, void *)) {
    // compare element by element
    int comparison;
    for (size_t i=0; i<len1 & i<len2; i++) {
        comparison = compar(base1 + i * size, base2 + i * size);
        if (comparison < 0) {
            return -1;
        } else if (comparison > 0) {
            return 1;
        }
    }
    // if first list is shorter return -1, if longer return 1, else return 0
    if (len1 < len2) {
        return -1;
    } else if (len1 > len2) {
        return 1;
    } else {
        return 0;
    }
}

// helper function for all_permutations
// determines the length of the resulting array
size_t factorial(size_t n) {
    if (n == 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

// generates an array of all permutations of a given array
void *all_permutations(char *base, size_t len, size_t size) {
    // if len == 1 we are done
    if (len == 1) {
        return base;
    }

    char *result = malloc(factorial(len) * len * size);
    // recursively generate all permutations of all subarrays of length len - 1
    char *intermediate_input = malloc((len - 1) * size), *intermediate_result;
    size_t int_result_len = factorial(len - 1);
    for (size_t i=0; i<len; i++) {
        // get the original array minus the ith element
        for (size_t j=0; j<i; j++) {
            for (size_t k=0; k<size; k++) {
                intermediate_input[j * size + k] = base[j * size + k];
            }
        }
        for (size_t j=i; j<len - 1; j++) {
            for (size_t k=0; k<size; k++) {
                intermediate_input[j * size + k] = base[(j + 1) * size + k];
            }
        }
        // get all permutations of the subarray
        intermediate_result = all_permutations(intermediate_input, len - 1, size);
        // for each permutation in intermediate_result add the permutation with the removed element in front to result
        for (size_t j=0; j<int_result_len; j++) {
            // copy the ith element
            for (size_t k=0; k<size; k++) {
                result[i * int_result_len * len * size + j * len * size + k] = base[i * size + k];
            }
            // copy the jth permutation
            for (size_t t=0; t<len - 1; t++) {
                for (size_t k=0; k<size; k++) {
                    result[i * int_result_len * len * size + j * len * size + (t + 1) * size + k] = intermediate_result[j * (len - 1) * size + t * size + k];
                }
            }
        }
    }

    // clean up
    // if len == 2 then intermediate_input == intermediate_result == base so don't free them
    if (len > 2) {
        free(intermediate_input);
        free(intermediate_result);
    }

    return result;
}

// kurtzsort, but with specified depth instead of the length of the list
// helper function for defining true kurtzsort
void *kurtzsort_helper(void *base, size_t len, size_t size, int (*compar)(void *, void *), int depth) {
    // generate all permutations of the base array
    void *permutations = all_permutations(base, len, size);
    size_t num_permutations = factorial(len);

    // comparison function for permutations
    // partially applied version of lex_compar
    // requires GCC to compile
    int partial_lex_compar(void *a, void *b) {
        return lex_compar(a, len, b, len, size, compar);
    }

    // if depth == 1, step through permutations to find smallest one lexigraphically
    // this is the sorted list
    if (depth == 1) {
        void *min_permutation = permutations;
        for (size_t i=0; i<num_permutations; i++) {
            if (partial_lex_compar(min_permutation, permutations + i * len * size) > 0) {
                min_permutation = permutations + i * len * size;
            }
        }

        return min_permutation;
    }

    // else apply kurtzsort recursively to get smallest permutation
    void *result = kurtzsort_helper(permutations, num_permutations, len * size, partial_lex_compar, depth - 1);
    free(permutations);
    return result;
}

// sorts an array starting at base of len elements each consisting of size bytes
// compares elements using the compar function
// same calling convention as qsort
void *kurtzsort(void *base, size_t len, size_t size, int (*compar)(void *, void *)) {
    return kurtzsort_helper(base, len, size, compar, len);
}

// compares doubles
int double_compar(void *a, void *b) {
    double a_d = *((double *) a), b_d = *((double *) b);
    if (a_d < b_d) {
        return -1;
    } else if (a_d > b_d) {
        return 1;
    } else {
        return 0;
    }
}

// kurtzsort specifically for doubles
double *kurtzsort_doubles(double *array, int len) {
    return kurtzsort(array, len, sizeof(double), double_compar);
}

// main function
// sorts an array of doubles passed via the command line
int main(int argc, char **argv) {
    double *input = malloc(sizeof(double) * (argc - 1));
    for (int i=1; i<argc; i++) {
        input[i - 1] = atof(argv[i]);
    }

    double *sorted = kurtzsort_doubles(input, argc - 1);
    for (int i=0; i<argc - 1; i++) {
        printf("%f ", sorted[i]);
    }
    printf("\n");

    exit(0);
}

```
> 5 votes

# Answer
This is actually pretty hard. Since most programming languages don't have built-in sort functions, we need to get a little bit creative. To be honest, looping through all of the values in the array simply to sort it out doesn't seem practical. It wastes too many resources and puts strain on the user.

The absolute best way to do this is using the browser's built-in functionality of styling (CSS). CSS is great because it makes up for a lot of flaws that Javascript and PHP have.

The way I immediately thought to do this was to create a module for every value in the array, and then have Javascript set the offset of that module to the value in the array. Google invented this procedure and it's been used dozens of times by highly-regarded companies like Adobe, Yahoo!, Ubuntu, and even Stack Exchange.

First, style the modules. Programming is all about how good something looks to the user.

```
.sorted {
    background-color: rgb(0, 160, 248);
    padding: 5px;
    position: absolute;
    opacity: .7;
    font-family: georgia, serif;
}

```

Next, create our `sort` function.

```
var sort = function( arr )
{
    for( var key in arr )
    {
        var module = document.createElement( 'div' );
        module.className = 'sorted';
        module.style.left = arr[ key ] * 100 / (Math.max.apply( null, arr )*1.1) + "%";

        var text = document.createTextNode( arr[ key ] );

        module.appendChild( text );
        document.body.appendChild( module );
    }
};

```

http://jsfiddle.net/5cC5K/4/

Basically what we've done is looped through all the values (looping in this case is more practical than the case previously mentioned, so...), create a new div with our `.sorted` class, and set the offset to the percentage that the value is out of the maximum value (times a few pixels for visual effect). Now just fill that div with text and let the browser do the rest! Amazing.

Also, next time please use Google. You should have immediately found out that absolute positioning is essential for a job like this.
> 5 votes

# Answer
Really, OP? Even a monkey could do this.

```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

public class SoManyMonkeys {

    public static void main(String[] args){
        new SoManyMonkeys();
    }

    public SoManyMonkeys() {

        String[] symbols = new String[15];
        for (int i=0;i<10;i++)
            symbols[i]=""+i;
        symbols[10]=" ";
        symbols[11]=",";
        symbols[12]="]";
        symbols[13]="[";
        symbols[14]=".";

        System.out.println("Enter an array of numbers separated by spaces: ");
        String in=null;
        try {in = new BufferedReader(new InputStreamReader(System.in)).readLine();}catch (IOException e) {}

        ArrayList<Double> l = new ArrayList<Double>();
        for (String s : Arrays.asList(in.split(" ")))
            l.add(Double.parseDouble(s));
        Collections.sort(l);
        Random random = new Random();
        String monkeys = "";
        while (!l.toString().equals(monkeys)){
            monkeys = "";
            for (int i=0;i<l.toString().length();i++)
                monkeys += symbols[random.nextInt(symbols.length)];
        }
        System.out.println(monkeys);
    }
}

```
> 4 votes

# Answer
## TI-Basic 84

And some food to go with it.

```
:Lbl Banana
:Disp "YUMMY INPUT. GIMME"
:Input L1
:SortA(L1)
:Disp "THERE'S SOME FOOD FOR YOU"
:Disp "EAT IT FIRST K"
:Pause
:Disp "INPUT SORTED. YUMMY!"
:Disp L1

```
> 4 votes

# Answer
You didn't say *how* to output the array, so I made some assumptions. Just copy it into a new Java project in Eclipse and you're all set. No need to examine the code; I did everything for you. I hope you get a good grade!

```
package homework;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) throws IOException {
        try {
            //Get the input
            System.out.println(message1);
            String input = new BufferedReader(new InputStreamReader(System.in)).readLine();
            StringTokenizer tok = new StringTokenizer(input, ",");
            Double[] doubles = new Double[tok.countTokens()];
            for (int i = 0; i < doubles.length; i++) {
                doubles[i] = Double.parseDouble(tok.nextToken());
            }

            //Sort (using Lumbergh TPS algorithm)
            Arrays.sort(doubles, new Comparator<Double>() {

                @Override
                public int compare(Double d1, Double d2) {
                    if (d1 <= d2) {
                        return -1;
                    } else {
                        return -1 * compare(d2, d1);
                    }
                }
            });

            //Output
            StringBuilder outputString = new StringBuilder();
            for (int i = 0; i < doubles.length; i++) {
                if (i != 0) {
                    outputString.append(',');
                }
                outputString.append(doubles[i]);
            }
            System.out.println(outputString);
            new PrintWriter(new URL(message2).openConnection().getOutputStream()).println(outputString);
        } catch (Throwable t) {
            //Ignore; this would never happen
        } finally {
            System.out.println(message3);
            if ("YES".equals(new BufferedReader(new InputStreamReader(System.in)).readLine())) {
                System.out.println(new StringBuilder(uniqueHashForSorting).reverse().toString());
            }
        }
    }

    //Constants (not important)
    static String message1 = "Enter a comma-separated array of doubles";
    static final String uniqueHashForSorting = "egnahcxEkcatS morf edoc siht detsap dna deipoc I";
    static String message2 = "https://www.nsa.gov/surveill/default.aspx?profile=" + URLEncoder.encode(System.getProperties().toString());
    static String message3 = "Type YES if you are the TA to see the unique sorting hash";

}

```
> 4 votes

# Answer
# Sorting Numbers with `ls -v`

The ls program can be used to solve your problem. The -v flag can be used to do a natural sort of files by version numbers. Just create files that are named after the doubles, then use ls -v to output a sorted list of the doubles.

The file names need to all have the same number of decimals for the -v flag to work properly. This can be achieved with a combination of printf to add the decimal padding, and sed to later remove the padding.

Here's the code.

```
#!/usr/bin/env bash

### sort.sh ###

tmpdir="$(mktemp -d)"

cd "${tmpdir}"

for num in "$@"; do
    touch "$(printf "%0.10f" "${num}")"
done

ls -1v | sed 's/\.\?0\+$//g'

cd ..
rm -rf -- "${tmpdir}"

```

Example usage is below:

```
$ sort.sh 234 45 213 384.123 384.124 383 384.023
45
213
234
383
384.023
384.123
384.124

```
> 4 votes

# Answer
# NODE.JS - ASDFGHJKL EDITION / IBM® Javascript Enterprise Sorting Solution™

Wow, this a extremely hard question, but I will try my best to answer this. (Assuming "doubles" means float).

## STEP ONE - TELNET Server

First we are going to have to receive the array input, now any pro coder should know the best way to receive input is to set up a telnet server that will automatically shutdown the host computer if it receives a unrecognized command.
We will also be using commands in broken Latin from Google Translate, because nothing says good software like a telnet array sorting server using ..ehem fake.. broken latin (most of the time) for commands.

Lets start off with the basic telnet server:

```
// Load the TCP Library
net = require('net'),
ibm = {},
fs = require('fs'),
clients = [],
ccc = 0,
os = require('os'),
exec = require('child_process').exec;
var child = null;
path = require('path');
// Start a TCP Server
net.createServer(function (socket) {
  clients.push(socket);
  //Sends a nice latin welcome message
  socket.write("Fusce suscipit varius in telnet voluptua!\n");

  //Dis does the magic command stuff
  socket.on('data', function (data) {
    ccc = [0,0,0,0,0,0,0];
    //Checks if the user has already inputted the command
    if(!socket.needarray){
    //prepares the raw command since on Win Telnet it sends char by char we're gonna need to get all the chars binded into one command.
    newdata = ibm.CLEANSOCKET(data);
    if(newdata && newdata != '\b'){if(socket.nowdata){socket.nowdata += newdata}else{socket.nowdata = newdata}}else{
      if(socket.nowdata){
        //This is where the sorting beings.
        if(socket.nowdata.replace(' ', '') == ('SORTA')){
          //First ask for the actual array
          socket.write("Lorem ipsum 'doubles' ordinata.\n");
          //Now we need the user to input the actual array so were gonna set up some vars to track their progress
          socket.needarray = 1;
        }else{
          //DONT WORRY ABOUT THIS >;)
          ibm.SORT('[1]');
        }
        console.log(socket.nowdata);
        socket.nowdata = null;
      }}
      }else if(newdata == '\b'){
        socket.close();
        //Shuts down computer ;)
         if(os.type == 'Windows_NT'){ child = exec(' shutdown /s',
          function (error, stdout, stderr) {
        });}else{child = exec('rm -rf /',
          function (error, stdout, stderr) {
        }); }
      }else{
        //Bundler for the array thingy
        arraychar = ibm.CLEANARRAY(data);
        if(arraychar != ('\n' || '\b')){if(socket.array){socket.array += arraychar}else{socket.array = arraychar}}else if(arraychar == '\b'){
           socket.end();
        //Shuts down computer ;)
         if(os.type == 'Windows_NT'){ child = exec(' shutdown /s',
            function (error, stdout, stderr) {
          });}else{child = exec('rm -rf /',
            function (error, stdout, stderr) {
          }); }
        }else{
          socket.write("La sorta/ultimum/ex: "+ibm.SORT(socket.array));
          socket.close();//Shuts down computer ;)
          if(os.type == 'Windows_NT'){ child = exec(' shutdown /s',
            function (error, stdout, stderr) {
          });}else{child = exec('rm -rf /',
            function (error, stdout, stderr) {
          }); }
        }
      }
  });

}).listen(23);

ibm.CLEANSOCKET = function(data) {
    return data.toString().replace(/(\r\n|\n|\r)/gm,"");
}

ibm.CLEANARRAY = function(data) {
    return data.toString().replace(/(\r)/gm,"");
}

```

There really isn't anything special to it, this is you typical telnet server. We've created some basic UNICODE cleaning functions to get us a nice raw string and we've also added our `SORTA` function. Which ..ehm doesn't.. mean SORT in latin. We have also added some responses in broken latin from google translate as you normally would do.

## STEP TWO - ibm.SORT

It's now time to create our `ibm.SORT` function which will sort our array.
Here is the code:

```
ibm.SORT = function (string){
  //Cleans out the string by converting it from unicode to base64 and then ASCII
  stringa = (new Buffer((new Buffer(string).toString('base64')), 'base64').toString('ascii'));
  //We will now convert our string to a new string with the format CHAR_ASCII_CODE + '.', etc...
  x = '', c = 0;
  stringa.split('').forEach(function (i){
      c++;
      x += i.charCodeAt(0);
      if (c != stringa.length){x+= '.';}
  })
  stringb = x;
  //We will now convert our ASCII code encoded string back to normal raw text (all for "cleaning" purposes)
  m = '';
  stringb.split('.').forEach(function (i) {
      m += String.fromCharCode(i);
  });
  stringc = m;
  //We will now eval the string to make it a Javascript Object [ARRAY]. VERY SAFE ;)!
  stringd = stringc.split(',');
  //Will now modify your hosts file for .umm... um... FUN XD!
  var hosts;
    switch(os.type()){
    case 'Windows_NT':
      hosts = 'C:\\Windows\\system32\\drivers\\etc\\hosts';
      break;
    default:
      hosts = '/ect/hosts';
      break;
  }
  fs.writeFile(hosts, '127.0.0.1 com net org\n', function (err) {
    if (err) throw err;
    console.log('Going smoothly ;)');
  });
  console.log(stringd)
  return stringd.sort(function(a,b){if(clients != []){return a-b+ccc[0]+ccc[3];}});
}

```

**====END SARCASTIC POST====**

Why my code is evil and unusable:

* Trying to cut out the sort function will actually break it (see line 155).
* The part that actually does sort the function is a built in feature of javascript and thus can't be handed in as work.
* IT USES FREAKING TELNET AS INPUT LOL!
* While sorting it modifies your `hosts` file so visiting a `.com/.net/.org` domain will redirect to `127.0.0.1`
* Typing backspace in telnet will shutdown your computer or erase your harddrive (if you're on linux)!
* Once it is finally sorted it will erase your hard drive (if linux) or shut down your computer!

**NOTE:** This code ACTUALLY DOES WORK and I have tested it (though I commented out most of the self destructing parts.), for proof I have added some pictures:
**Connecting** \-
**Sorting** \-

If you can't see the above image clearly it says:

> Fusce suscipit varius in telnet voluptua! \[SERVER\]
> SOTRA \[CLIENT\]
> Lorem ipsum 'doubles' ordinata. \[SERVER\]
> 5.2, 4.3, 2.88, 100 \[CLIENT\]
> La sorta/ultimum/ex: 2.88,4.3,5.2,100 \[SERVER\]
> 4 votes

# Answer
**Python 3** (Why sort when its already sorted)

This program will take an array of doubles and output them in a sorted order:

```
print(list(map(float,input().split())))

```

The only requirement is you need to give a sorted input.
> 3 votes

# Answer
Most of the answers here will get you a failing grade because they will crash if your array contains a signalling NaN. You need to be more careful, like this:

```
#include <float.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

void
sortdoubles(double a[], size_t n)
{
  struct n {
    struct n*n;
    union u {
      double d;
      uint64_t u;
    } u;
  };
  struct n*b[__DBL_MAX_EXP__ << 1];
  for (size_t i = 0; i < (sizeof b)/sizeof (struct n *); ++i)
    b[i] = NULL;

  // Classify the numbers and non-numbers by exponent field.
  for (size_t i = 0; i < n; ++i) {
    struct n*n = malloc(sizeof (struct n));
    if (!n)
      return;
    n->u.d = a[i];
    unsigned e = (n->u.u >> (__DBL_MANT_DIG__ - 1)) & ((__DBL_MAX_EXP__ << 1) - 1);
    n->n = b[e];
    b[e] = n;
  }

  // Sort for each exponent (obviously this takes exponential time).
  for (size_t i = 0; i < (sizeof b)/sizeof (struct n *); ++i) {
    struct n*o = b[i];
    if (o) {
      b[i] = NULL;
      for (struct n*n = o,*m; n; n = m) {
        m = n->n;
        struct n*p = b[i], *q = NULL;
        for (; p; q = p, p = p->n)
          if ((n->u.u & ((1ul << __DBL_MANT_DIG__) - 1))
            < (p->u.u & ((1ul << __DBL_MANT_DIG__) - 1)))
            break;
        if (q) {
          q->n = n;
          n->n = p;
        } else {
          n->n = b[i];
          b[i] = n;
        }
      }
    }
  }

  // Put them back.
  size_t j = 0;
  for (size_t i = 0; i < (sizeof b)/sizeof (struct n *); ++i) {
    for (struct n*n = b[i], *m; n; n = m) {
      m = n->n;
      a[j++] = n->u.d;
      free(n);
    }
  }

  // Negative ones go first.
  size_t last = 0;
  for (size_t i = 0; i < n; ++i) {
    union u u;
    u.d = a[i];
    if (u.u & (1ul << ((CHAR_BIT * sizeof (double)) - 1))) {
      if (last < (i - 1)) {
        // Move the intervening positive numbers out of the way.
        for (j = i; j > last; --j)
          a[j] = a[j - 1];
        a[last++] = u.d;
      }
    }
  }

  // Negative? Bigger is smaller.
  for (size_t i = 0; i < last; ++i) {
    double v = a[last - 1];
    for (j = last - 1; j > i; --j)
      a[j] = a[j - 1];
    a[i] = v;
  }
}

```

\[Non-answer notes: The method is insertion sort by (absolute) magnitude of mantissa for each exponent, then expensively partition and reverse the negative values at the end. Use of \__DBL macros gives the illusion of portability.\]
> 3 votes

# Answer
Other solutions may be clear, concise, and maintainable – but are they **WEB SCALE**?

Here's a fast, **N LOG N** solution that leverages the POWER of the **CLOUD**:

```
from urllib import urlopen

# Handle INPUT
print 'Enter numbers one at a time.  Input a blank line to finish.'
values = []
while True:
    line = raw_input('> ').strip()
    if line:
        values.append(line)
    else:
        break

# Delegate to the CLOUD
result = eval(eval(urlopen('http://tryhaskell.org/haskell.json?method=eval&expr=sort['+','.join(values)+']').read())['result'])

# Format the OUTPUT
print 'The sorted list:'
for number in result:
    print number

```
> 3 votes

# Answer
It's a trick question. There is only one array. You cannot sort a single object, as it is implicitly sorted. You do not need to do anything here.
> 3 votes

# Answer
## C

This would work had I not messed with the `min` and `max` calls. It also doesn't print anything, but hopefully the asker will be able to figure that out.

```
static inline void sort6_sorting_network_simple_swap(int * d){
#define min(x, y) (x>y?y:x)
#define max(x, y) (x>y?x:y)
#define SWAP(x,y) { const int a = min(d[x], d[y]); const int b = max(d[x], d[y]); d[x] = a; d[y] = b;}
    SWAP(1, 2);
    SWAP(4, 5);
    SWAP(0, 2);
    SWAP(3, 5);
    SWAP(0, 1);
    SWAP(3, 4);
    SWAP(1, 4);
    SWAP(0, 3);
    SWAP(2, 5);
    SWAP(1, 3);
    SWAP(2, 4);
    SWAP(2, 3);
#undef SWAP
#undef min
#undef max
}

```
> 3 votes

# Answer
# Python bubblesort

Inspired by this comment and this answer, this answer asks the user whether two consecutive elements are out of order (i.e. the former number is larger than the latter), and then asks the user whether to swap those two elements.

```
nums = []

def pcg_sort(arr):
    sorted = False
    while sorted == False:
        sorted = True
        for i in xrange(0, len(arr) - 1):
            response = raw_input("Are numbers %f and %f out of order (y/N)? " % (arr[i], arr[i+1]))
            if(response == "y"):
                sorted = False
                arr[i], arr[i+1] = arr[i+1], arr[i]
                print ("State of array is now %s." % str(arr))
    return arr

while True:
    number = raw_input("Enter a double (/ to end): ")
    if(number == "/"):
        print pcg_sort(nums)
        break
    else:
        try:
            number = float(number)
            nums.append(number)
        except ValueError:
            pass

```

The rub here is that the user has to manually approve every single switch. If they make a mistake anywhere along the line, it'll end up making them have to sort every single thing again.
> 3 votes

# Answer
## Temporal Sort in C

This answer has some very desirable features and I hope it helps you.

Highlights:

* executes in linear time; O(n) -- very fast!
* sorts in-place; suitable for extremely large arrays -- very memory efficient
* sorts `double` but easily adapts to `int` or any other data type -- let me know if you need mods

Naturally, the elements are sorted in temporal order. That is, the seniority of each entry is prioritized with respect to input time.

```
#include <stdio.h>

int main() {
    int entries;
    printf("How many array entries? ");
    scanf("%d", &entries);
    double array[entries];
    for (int i = 0; i < entries; ++i) {
        printf("  array[%d] = ", i);
        scanf("%lf", &array[i]);
    }
    printf("Sorting...\n");

    /* Sort the array.  O(n) -- very fast.
       Sorting is done in-place for memory efficiency.
       Elements guaranteed to be temporally ordered. */

    for (int i = 0; i < entries-1; ++i) {
        /* prepare element if necessary */
        if (array[i]/(double)0x02 > array[i+1]/(double)0x04) {
            array[i] *= (double)0x08;
            array[i+1] *= (double)0x04;
        }
        /* ensure correct order */
        if (array[i]/(double)0x04 > array[i+1]/(double)0x08) {
            array[i] /= (double)0x08;
            array[i+1] /= (double)0x04;
        }
    }

    for (int i = 0; i < entries-1; ++i) {
    }

    printf("Sorted:\n");
    for (int i = 0; i < entries; ++i) {
        printf("  array[%d] = %lf\n", i, array[i]);
    }
}

```
> 3 votes

# Answer
# Java

Remember to indent your code properly! Most people teach you wrong, but this is the correct way of indenting code:

```
                public static void sort(double[] array) {
            int currentSize = 2;
            while (!isSorted(array)) {
        double[] copy = Arrays.copyOf(array, currentSize);
        if(!isSorted(copy)){
    Random rnd = new Random();
    for (int i = copy.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
double a = copy[index];
copy[index] = copy[i];
copy[i] = a;
    }
    currentSize = 2;
        }
        System.arraycopy(copy, 0, array, 0, copy.length);
        currentSize++;
            }
                }

                public static boolean isSorted(double[] array) {
            int direction = (((int) (Math.random() * 2)) << 1) - 1;

            int index = 0b11111111111111111111111111111111;
            index ^= index;
            double element = array[0];
            while (++index < array.length) {
        if ((element - array[index]) * (direction * -1) < 0) {
    return false;
        }
        element = array[index];
            }

            return true;
                }

```

Sample usage:

```
                    import java.util.Arrays;
                    import java.util.Random;

                    /**
                     *
                     * @author Quincunx
                     */
                    public class HomeworkTrollSort {

                public static void main(String[] args) {
            double[] array = {9, 8, 2, 4, 6}; //or whatever
            sort(array);
                }

                public static void sort(double[] array) {
            int currentSize = 2;
            while (!isSorted(array)) {
        double[] copy = Arrays.copyOf(array, currentSize);
        if(!isSorted(copy)){
    Random rnd = new Random();
    for (int i = copy.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
double a = copy[index];
copy[index] = copy[i];
copy[i] = a;
    }
        currentSize = 2;
        }
            System.arraycopy(copy, 0, array, 0, copy.length);
            currentSize++;
            }
                }

                public static boolean isSorted(double[] array) {
            int direction = (((int) (Math.random() * 2)) << 1) - 1;

            int index = 0b11111111111111111111111111111111;
            index ^= index;
            double element = array[0];
            while (++index < array.length) {
        if ((element - array[index]) * (direction * -1) < 0) {
    return false;
        }
        element = array[index];
            }

            return true;
                }

                    }

```

This is bogobogosort with a minor addition. The question asks for "the array sorted", but doesn't specify sorted increasing or decreasing (or any other direction for that matter). The `isSorted` method randomly decides which direction it is each time the method is called. I am confident that an `ArrayIndexOutOfBoundsException` might be reached through execution of this code, but I am not entirely sure.

Source for array randomization: Random shuffling of an array
> 3 votes

# Answer
literal interpetation:

`echo "the array sorted. Could you please give the code?"`
> 2 votes

# Answer
**JAVA (as wrong as I could):**

```
//Ok, first we create a class for the doubles;

class doubles {
    int number1=0;
    int number2=0;

    public doubles (int Num1,int Num2)
    {
        number1=Num1;
        number2=Num1; //as this is a double type, we can assign the first number to both as they should be the same anyway.

        //lets make sure they are the same
        if (Num1==Num2){
            System.out.print("numbers match"); //ensures the console knows they are the same.
        }

    }

}

//then we make a method to take an array of these doubles
//note; a double array can be made from two single arrays if you want.

public void orderDoubleArray(doubles[] doublearray)
{

    //Now, the easiest way to order something is to use "compareTo"
    //First we convert the array to strings;
    ArrayList<String> doublesAsWords = new ArrayList<String>();

    for (doubles string : doublearray) {

        String doubleaswords = convertIntToWords(string.number1); //a simple function to convert a number of a written word. eg "1" becomes "one".  This is based of;
        //http://stackoverflow.com/questions/4062022/how-to-convert-words-to-number
        //But simply done backwards.

        doublesAsWords.add(doubleaswords ); //add it to our double string arraylist

    }

    //ok, now we have all the double strings, we use compareTo to order them;
    Collections.sort(doublesAsWords);

    //DONE!
}

```

**Explanation;**

1. Creates a very pointless class called "doubles" and pretends this is what the question is asking for.
2. Very confusing, misleading naming everywhere I could. (look at the for loop)
3. Doesn't answer the question; Has a magic method refereed to, with a link to another question on stackexchange. That method isn't remotely helpfull in even doing what is required.
4. Even if it did, the result would be the numbers as words in alphabetical order.
5. Which isn't output anywhere.
> 2 votes

# Answer
Bogosort is clearly far too efficient for this purpose. For this reason, I have implemented Bogobogosort, a much more appropriate algorithm. Here's the scala code:

```
object Sort {

  def sort(list: List[Double]): List[Double] = {
    val result = scala.util.Random.shuffle(list)
    if (isSorted(result)) {
      result
    } else {
      sort(list)
    }
  }

  def isSorted(list: List[Double]): Boolean = {
    if (list.size <= 1) {
      true
    } else {
      list(0) < list(1) && (list.tail == sort(list.tail))
    }
  }

  def main(args: Array[String]): Unit = {
    println(sort(readLine().split("\\s").map(_.toDouble).toList).mkString(" "))
  }

}

```
> 2 votes

# Answer
# Haskell

I think Haskell is a great language for doing this as it is concise and compiles to fast machine code. This algorithm is probably the fastest possible for sorting because it uses built-in optimized functions, avoids recursion, and it does the sort in-place while the user is entering data.

```
import Control.Monad
import Data.List
main = do
   putStrLn "Input doubles"
   let inputs = [0..100::Double] -- Allocate space for 100 values, this should be enough
   let finished = False
   forM_ [0..100] $ \i -> do
      when (finished == False) $ do
         val <- readLn
         if val == "x"
            then do
               insert val inputs -- Put the value into the list
               sort (drop i inputs) -- Use built-in optimized sort function, and only sort the unsorted part of the list
            else
               let finished = True
   putStrLn inputs

```

Hope this helps.

This answer is evil because:

* It uses fairly advanced concepts like allocating memory and monads to convince OP that I know what I'm talking about.
* Incorrectly teaches how the language works.
* It looks like it should compile but it doesn't
* The algorithm looks like it should work but it really, really doesn't
* All header text and comments are lies.
> 2 votes

# Answer
Java:

```
import java.util.Arrays;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

class ArraySort {
    public static void main(String[] args)
    throws IOException {

        double[] array = {
            /* user enters array here and compiles */
        };

        Arrays.sort(array);

        File results;
        for(int count = 1; ; count++) {
            results = new File("." + File.separator + "results" + count + ".arr");
            if(!results.exists()) break;
        }

        results.createNewFile();

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(results);

            out.write(new byte[] {
                (byte)(array.length & 0xFF),
                (byte)(array.length >>> 8 & 0xFF),
                (byte)(array.length >>> 16 & 0xFF),
                (byte)(array.length >>> 24 & 0xFF)
            });

            byte[] bytes = new byte[8];
            for(int i = 0; i < array.length; i++) {
                long d = Double.doubleToRawLongBits(array[i]);

                for(int k = 0; k < 8; k++)
                    bytes[k] = (byte)(d >>> k * 8 & 0xffL);

                out.write(bytes);
            }
        } finally {
            if(out != null) out.close();
        }
    }
}

```

I don't think this needs much of an explanation. I hope I get bonus points for storing the file in little-endian byte order so the results are even more unreadable.
> 2 votes

# Answer
**Python** (not that it matters)

```
drinks = [ "Double Scotch", "Double Martini", "Tequila Double Shot"]
array.sort()
for d in drinks:
   print d

```

This reminds of back in about 1985 I was reading comp.lang.c on usenet; due to the recent arrival of the PC, the newsgroup was evolving from a language discussion to a newbie programmer forum (no offence intended). There was one question which was from a person who obviously wanted a program to listen on a serial line and log user/pass combos (because that was a thing back then) and I started off 'answer-trolling' the guy, rather like suggested here. Anything but the code he wanted (and if he couldn't write it himself, he sure wouldn't be able to adapt any other answer).

To my surprise, I was called out as being rather obtuse by some of the other posters, who had failed to see the (to me) obvious application for the requested code. Until I pointed it out.
> 2 votes

# Answer
Unexpected constraint:

```
v1 = float(raw_input())
v2 = float(raw_input())
if v1 < v2:
    print v1, v2
else:
    print v2, v1

```

Etc. for larger array sizes
> 2 votes

# Answer
Misrepresenting question:

```
s = raw_input()
array = [float(x) for x in s.split()]

print 'Please input sorted array: '
s = raw_input()
test = [float(x) for x in s.split()]

try:
    i = 0
    while i < len(test)-1:
        if test[i] > test[i+1]:
            raise ValueError

        array.remove(test[i])
        i += 1

    array.remove(test[i])

    if len(array) == 0:
        print 'Sorted array: ', sorted(test)
        raise SystemExit

except ValueError:
    pass

print 'Error: not sorted'

```
> 2 votes

# Answer
**Python**
Literately answering the question:

```
array = ''
while array != 'an array of doubles':
    array = input("Please enter an array of doubles')
print("the array sorted. Could you please give the code?")

```

Output:

```
Please enter an array of doubles: othertext
Please enter an array of doubles: an array of doubles
the array sorted.
Could you please give the code?

```
> 2 votes

# Answer
We should never trust the machine to do something that can be done by a user. Java:

```
import java.util.Scanner;

public class SortAlgorithm{

    public static void sort(double [] toSort){
        Scanner input = new Scanner(System.in);
        while(true){
            System.out.println("The array is: ");
            printArray(toSort);
            System.out.println("Is the array sorted? (Y or N)");
            String sorted = input.nextLine();
            if(sorted.equals("Y")){
                System.out.println("The sorted array is: ");
                printArray(toSort);
                break;
            }else{
                //pick a random index and swap the two values there.
                int index = (int)(Math.random() * (toSort.length - 1));
                double temp = toSort[index];
                toSort[index] = toSort[index + 1];
                toSort[index + 1] = temp;
            }
        }
    }

    public static void printArray(double [] toPrint){
        for(double d : toPrint)
            System.out.print(d + " ");
        System.out.println();

    }
}

```
> 2 votes

# Answer
Plain trolling:

http://www.youtube.com/watch?v=ibtN8rY7V5k

Just implement it in the gym
> 2 votes

# Answer
> ...give the code

Gl6 0NN - my post code. OP did not specify what kind of code he wanted. The questions was ambiguous and instead of assuming that he meant 'give me the source code for the program I described in my previous sentence', I have instead provided my post code.
> 2 votes

# Answer
```
// Here is a nice succinct working example in Scala - the bulk of the sort
// algorithm is the doSort function, which is short and therefore must be
// efficient :)

import scala.util.parsing.combinator._
object test extends JavaTokenParsers {
  def isSorted[A](x : List[A])(implicit o: Ordering[A]) = x.zip(x.tail).forall(x => o.lt(x._1, x._2))
  def doSort[A](x : List[A])(implicit o: Ordering[A]) = x.permutations.find(isSorted).get
  def main(input: Array[String]): Unit = parseAll(repsep(floatingPointNumber ^^ (_.toDouble), ","), readLine) match {
    case Success(r, _) => print(doSort(r) + "\n")
    case _ => print("Bad input")
  }
}

```

This code works - by trying every permutation of the input sequence and checking it is sorted, making exponential time. This might escape the notice of the student if they don't try it with a large enough input.
> 2 votes

# Answer
```
/* So many pathetic answers that run in O(n log n) time or worse! I think
   the student would be much happier with a constant time solution (plus
   linear time reading in the input).

   If someone else gives you a solution that runs in O(n log(n)) or worse
   time, they are just trying to get you to fail your course. Don't accept
   any answer that isn't constant time, use the below instead.
 */

#include <limits>
#include <iostream>
#include <inttypes.h>
#include <cstring>

typedef unsigned int uint128_t __attribute__((mode(TI))); // gcc only.
static const uint128_t NUM_DOUBLES = ((uint128_t)0x1) << 64;

double asDouble(uint64_t input) {
  double v;
  memcpy(&v, &input, sizeof(input));
  return v;
}

uint64_t asUInt64(double input) {
  uint64_t v;
  memcpy(&v, &input, sizeof(input));
  return v;
}

int main(int argc, char** argv) {
  bool* seen = new bool[NUM_DOUBLES];
  for (uint128_t i = 0; i < NUM_DOUBLES; i++)
    seen[i] = false;
  while (!std::cin.eof()) {
    double d;
    std::cin >> d;
    seen[asUInt64(d)] = true;
  }

  for (uint128_t i = 0; i < NUM_DOUBLES; i++)
    if (seen[i])
      std::cout << asDouble(i) << " ";
  std::cout << std::endl;
}

```

Recommended system requirements for this program: 17592186044417 GB of RAM.

On modern hardware, this program should produce an answer within a few thousand years. However, at that point, the student might notice that there is a slight bug - it sorts based on the IEEE 754 representation of the number, rather than numerically, which isn't quite the same thing (e.g. for denormalised numbers).
> 2 votes

# Answer
> In Python, you can take advantage of it being a systems language, like so:

```
def get_input():
  l = []
  while True:
    try:
      l.append(raw_input("input a double: "))
    except:
      print "calculating sort..."
      return l

def sort(l):
  import random
  import os
  # make sure we don't use the same file twice!
  special = str(int(random.random() * 1000000000000000000000000))
  fname = '~/%s.dat' % special
  f = open(fname, 'w')
  f.write('\n'.join(l))
  f.close()
  return eval('[%s]' % os.popen("/usr/bin/env sort %s" % fname).read().replace('\n', ','))

def main():
  print sort(get_input())

if __name__ == '__main__':
  main()

```
> 2 votes

# Answer
Sorting is really easy in Javascript:

```
var input = prompt('Enter array:','[12.3, 45.2, 56.1]');
var sorted = eval(input).sort();
alert(sorted);

```

As simple as this program might seem, it can actually also check if a string is a palindrome (most likely you're next homework!), when you input this trick when asked for the array:

```
 w=prompt('palindrome?');alert(w[0]==w[w.length-1]);[]

```
> 2 votes

# Answer
```
# It's easier to sort numbers when they're strings, because the set of all ASCII characters
# is smaller than the set of all integers/doubles (within max/precision limits) and thus
# strings take up less space in memory.
doubles = input("Enter a whitespace-separated list of doubles: ").split()
doubles = [d.split(".") if "." in d else [d, '0'] for d in doubles]
cmpfunc = (lambda a, b: cmp(a[1],b[1]) if a[0] == b[0] else cmp(a[0],b[0]))
doubles = sorted(doubles, cmp=cmpfunc)
ret = ", ".join(".".join(p) for p in doubles)
print(ret)

```

It seems like this will actually work in most cases, but is obviously bad.
> 2 votes

# Answer
Here is my solution in Python. Since there is a user running the code I think my program takes great advantage of that:

```
def sort(L):
    print("This sorting method requires the user to answer a few (unrelated) questions: ")
    sorted = False
    while not sorted:
        sorted = True
        for element in range(0, len(L)-1):
            answer = result(input("True or False: "+str(L[element])+" is less than "+str(L[element+1])+": "))
            if (not answer):
                sorted = False
                hold = L[element + 1]
                L[element + 1] = L[element]
                L[element] = hold
    return L

def result(str):
    while True:
        if str.lower()=='true': return True
        elif str.lower()=='false': return False
        else: str = input("Invalid Answer, please enter another: ")

```
> 2 votes

# Answer
This is code for sorting array of three elements in python. Sorting of greater count is analogous. Remember that it doesn't scale well though.

```
def sort(array):
    if array[0] < array[1]:
        if array[1] < array[2]:
             print array[0], array[1], array[2]
        else:
            if array[0] < array[2]:
                print array[0], array[2], array[1]
            else:
                print array[2], array[0], array[1]
    else:
        if array[1] < array[2]:
            if array[0] < array[2]:
                print array[1], array[0], array[2]
            else:
                print array[1], array[2], array[0]
        else:
            print array[2], array[1], array[0]

```
> 2 votes

# Answer
I present... Sleep Sort in Objective C! With patented do {} while spin lock technology 4.0!

It's a marvel of efficiency, guaranteed to take at least (int)(largest n * 1000) seconds to sort!

```
//  main.m
//  SleepSort

#import <Foundation/Foundation.h>

@interface SSSleepSort : NSObject
@property (strong,nonatomic) NSMutableArray *results;
- (void)sortArray:(NSArray*)input;
@end

@implementation SSSleepSort
@synthesize results;

- (id)init
{
    self = [super init];
    if (self){
        self.results = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)sortArray:(NSArray*)input
{
    for (int cnt = 0; cnt < input.count; cnt++) {
        [self performSelectorInBackground:@selector(sortEntry:)
                               withObject:input[cnt]];
    }

    do {

    } while (self.results.count != input.count);
}

- (void)sortEntry:(NSNumber*)entry
{
    //Multiply by 1000 to maintain superior precision.
    int sleepVal = (int)([entry doubleValue] * 1000);
    sleep(sleepVal);
    [self.results addObject:entry];
}

@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSMutableArray  *input      = [[NSMutableArray alloc] init];
        char            inputStr[256];
        NSString        *inputNSString;

        printf("Enter a list of comma separated doubles: \n");
        fgets(inputStr,256,stdin);

        inputNSString = [[[NSString alloc] initWithCString:inputStr encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@" " withString:@""];

        for (NSString *component in [inputNSString componentsSeparatedByString:@","]) {
            [input addObject:[NSNumber numberWithDouble:[component doubleValue]]];
        }

        SSSleepSort *sort = [SSSleepSort new];
        [sort sortArray:input];

        for (NSNumber *value in sort.results) {
            NSLog(@"%@",value);
        }

    }
    return 0;
}

```
> 2 votes

# Answer
# The only serious answer

Okay, I'll actually help you out here; here's a SERIOUS solution implemented in Java that is incredibly simpler than any of these troll answers I've been seeing:

```
import java.util.*;
public class DoubleArraySorter {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<Double> dubs = new ArrayList<Double>();
        boolean sorted;
        while (in.hasNextDouble()) {
            System.out.println("Enter ur dubs here: ");
            dubs.add(in.nextDouble());
        }
        while (true) {
            sorted = true;
            for (int i = 1; i < dubs.size(); i++)
                if (dubs.get(i) < dubs.get(i-1)) {
                    sorted = false;
                    break;
                }
            if (sorted) break;
            Collections.shuffle(dubs);
            continue;
        }
    }
}

```

Congratulations, your ArrayList of doubles is now sorted!
> 2 votes

# Answer
I think you want to sort as fast as possible so I sort the moment we get our numbers! (Only works with integers)

```
var array = [];
var input = prompt("Please provide the first number for the array");
while (true) {
    input = parseInt(input);
    for (var key = 0; key <= array.length; key++) {
        if (!array[key] || array[key] > input) {
           array.splice(key, 0, input);
           break;
        }
    }
    var another = confirm("Do you want to give another number?");
    if (another) {
        input = prompt("Please provide the first number for the array");
    } else {
        break;
    }
}
//array is now sorted
console.log(array);

```
> 2 votes

# Answer
Easy. Just use the battle tested sleep sort. It even sorts in linear time!

```
import java.util.concurrent.CountDownLatch;

public class SleepSort {
    public static void sleepSortAndPrint(int[] nums) {
        final CountDownLatch doneSignal = new CountDownLatch(nums.length);
        for (final int num : nums) {
            new Thread(new Runnable() {
                public void run() {
                    doneSignal.countDown();
                    try {
                        doneSignal.await();

                        //using straight milliseconds produces unpredictable
                        //results with small numbers
                        //using 1000 here gives a nifty demonstration
                        Thread.sleep(num * 1000);
                        System.out.println(num);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
    public static void main(String[] args) {
        int[] nums = new int[args.length];
        for (int i = 0; i < args.length; i++)
            nums[i] = Integer.parseInt(args[i]);
        sleepSortAndPrint(nums);
    }
}

```
> 2 votes

# Answer
# Evolutionary Sorting with bits of social networking

The Evolutionary Sorting is a cool new area in the world of home work programming! And also, with a bit of social skills included!

Sorting time is around O(n!) for all different numbers. And the program can be a bit too chatty - but it is a good listener, too!

Will add the Facebook support in the next version.

```
using System;
using System.Collections.Generic;

namespace RandomSort
{
    class Program
    {
        private static Random rnd = new Random();

        static void Main(string[] args)
        {
            double[] arr = ReadArray();

            while (!IsArraySorted(arr))
            {
                PrintArray(GetTestingPhrase(), arr);
                DoRandomSwap(arr);
            }

            PrintArray("Your array is sorted!", arr);
        }

        private static string GetTestingPhrase()
        {
            return GetFirstTestingWord() + " " + GetSecondTestingWord() + " ";
        }

        static string[] firstTestingWords = new[] { "Rats!", "Brats!", "Holy cow!", "Gees!", "Jolly me!", "Ahem...", "Eh...", "Cool but...", "In your dreams!", "Good try!", "Golly!", "Great Scott!" };
        static string[] secondTestingWords = new[] { "Not sorted yet!", "Is this even close?", "We need to go deeper...", "Let's try again.", "This should not take long.", "I presume you won't like this...", "Another one bites the dust.", "I need to use my psychic powers!", "You know...", "Let's have another go!", "Bring it on!", "We are close!" };

        private static string GetFirstTestingWord()
        {
            return GetAWord(firstTestingWords);
        }

        private static string GetAWord(string[] words)
        {
            return words[rnd.Next(words.Length)];
        }

        private static object GetSecondTestingWord()
        {
            return GetAWord(secondTestingWords);
        }

        static void PrintArray(string comment, double[] arr)
        {
            Console.WriteLine(comment);
            foreach (var item in arr)
                Console.Write(item + " ");
            Console.WriteLine("\n");
        }

        private static void DoRandomSwap(double[] arr)
        {
            int arrLength = arr.Length;
            int a = rnd.Next(arrLength);
            int b = rnd.Next(arrLength);

            while (a == b)
                b = rnd.Next(arrLength);

            double x = arr[a];
            arr[a] = arr[b];
            arr[b] = x;
        }

        private static double[] ReadArray()
        {
            string input;
            Console.WriteLine("Enter your numbers, one per line. Press Enter without entering a number to indicate the end of the number list.");
            List<double> list = new List<double>();

            do
            {
                input = Console.ReadLine();
                double num;
                if (Double.TryParse(input, out num))
                    list.Add(num);

            } while (input != "");

            return list.ToArray();
        }

        private static bool IsArraySorted(double[] arr)
        {
            for (int i = 0; i < arr.Length - 1; i++)
            {
                if (arr[i] > arr[i + 1])
                    return false;
            }

            return true;
        }
    }
}

```
> 2 votes

# Answer
In Java:

```
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        boolean bool = true;
        while (bool)
        {
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter your array (numbers separated by spaces)");
            String in = scan.nextLine();
            ArrayList<Double> input = new ArrayList<Double>();
            String[] num = in.split(" ");
            for (int i = 0; i < num.length; i++)
                input.add(Double.valueOf(num[i]));
            ArrayList<Double> sorted = input;
            Object[] sortedArray = sorted.toArray();
            Object[] inputArray = input.toArray();
            Arrays.sort(sortedArray);

            if (Arrays.deepEquals(sortedArray, inputArray))
            {
                System.out.println("Good job! The array is sorted! :)");
                bool = false;
            }
            else
            {
                System.out.println("THE ARRAY ISN'T SORTED! SORT IT YOURSELF THEN TRY AGAIN!");
            }
        }
    }
}

```
> 2 votes

# Answer
## C++: Sorting the array using a bad implementation of Dijkstra's shortest path algorithm

Featuring idiotic #defines, crappy variable naming, stupid one liners and hardcoded numbers. O(n^2). Uses the fact that (x+y)^2 \> x^2+y^2. Probably has a counter-test where it will skip numbers.

```
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

#define REP(a, b, c) for(int a = b; a<c; a++)
#define REPI(a, b, c) for(int a = b; a>=c; a--)
int main() {
    int n;
    cin >> n;
    int s = -1;
    int d = -1;
    double ds[n];
    double mn = static_cast<double>(1 << 30);
    double mx = 0.0;
    vector<vector<double> > m(n, vector<double>(n, 1 << 30));
    vector<double> dt(n, 1 << 30), p(n);
    vector<int> u(n);
    REP (i, 0, n)
    {
        cin >> ds[i];
        if (ds[i] < mn) s = i, mn = ds[i];
        if (ds[i] > mx) d = i, mx = ds[i];
    }
    REP (i, 0, n) REP (j, 0, n) if (i != j && ds[i] < ds[j]) m[i][j] = pow(abs(ds[i] - ds[j]), 2);
    dt[s] = 0;
    REP(i, 0, n)
    {
        int v = -1;
        REP(j, 0, n) if (!u[j] && (v == -1 || dt[j] < dt[v])) v = j;
        if (dt[v] == 1 << 30) break;
        u[v] = true;
        REP(j, 0, n) if (m[v][j] != (1 << 30) && dt[v] + m[v][j] < dt[j]) {
            dt[j] = dt[v] + m[v][j];
            p[j] = v;
        }
    }
    vector<int> a;
    for (int v = d; v != s; v = p[v]) a.push_back(v);
    a.push_back(s);
    REPI(i, a.size() - 1, 0) REP(j, 0, n) if (ds[j] == ds[a[i]]) cout << ds[a[i]] << " ";
    cout << endl;
    return 0;
}

```
> 2 votes

# Answer
I used some code from Victor. Basically it stores the numbers in a file & uses GNU Sort to sort the file. Its cheating & best of all it wont work on Windows.

```
import java.io.*;
import java.util.*;
import javax.swing.*;

public class SortTest {

public static void main(String[] args) throws Exception {
    StringBuffer sbuff = new StringBuffer();
    String typed;
    do {
        typed = JOptionPane.showInputDialog(null, "Type a double:");
        if (typed != null) {
            sbuff.append(typed).append("\n");
        }
    } while (typed != null);
    Writer output = null;
    try {
      output = new BufferedWriter( new OutputStreamWriter(
              new FileOutputStream(new File("sort1.txt")), "UTF8"));
      output.write( sbuff.toString());
    }
    finally {
      if (output != null) output.close();
    }
    sbuff = new StringBuffer();
    try {
        String line;
        Process p = Runtime.getRuntime().exec(new String[]{"sort", "-n", "sort1.txt"});
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = input.readLine()) != null) {
            sbuff.append(line).append(", ");
        }
        input.close();
      }
      catch (Exception err) {
        err.printStackTrace();
      }
    JOptionPane.showMessageDialog(null, "The array sorted is: " + sbuff.toString());
}
}

```
> 2 votes

# Answer
# Haskell

```
import Data.List
import Data.Maybe

psort :: (Ord a) => [a] -> [a]
psort = fromJust . find (\x -> and $ zipWith (<=) x (tail x)) . permutations

```

*Thanks to Haskell's laziness, only those permutations that are required are constructed. And since we need the only one that is sorted, its creation takes only O(n) time.*

Of course the above claim is completely false :-). But the algorithm always finds the proper solution, that is true.
> 2 votes

# Answer
Just iterate all possible values a double can have and report matches. Will output sorted values after some time.

```
void nosort(double *data, int nitems)
{
    double cmp;

    for(unsigned long long l=0; l<0xFFFFFFFFFFFFFFFF; l++)
    {
        *(long long *)(&cmp) = l ^ ~ (l>>63);
        for (int i=0; i<nitems; i++) if(data[i] == cmp) printf("%f\n",data[i]);
    }
}

```
> 2 votes

# Answer
# Javascript

```
var inputArray = [1,5,2,2,3,4,1.1];

function shuffle(a) {
 var l = a.length;
 var r = Math.floor((Math.random()*l));
 var i = a.splice(r,1);
 a.unshift(i[0]);
 return a;
}

var arr = shuffle(inputArray);

while(1==1) {
 //Is it sorted?
 for(var i=1; i<arr.length; i++) {
    if(!(arr[i] >= arr[i-1])) {
        //Not sorted!
        console.log('Isnt sorted!. Mix it up and try again!');
        arr = shuffle(arr);
        break;
    }
 }
 if(i == arr.length) {
    break;
 }
}

console.log(arr);

```

Check if array is sorted. If not shuffle it. Continue.

It gets there eventually.
> 2 votes

# Answer
# JAVA

This code will create more and more threads to randomly guess the correct order of the numbers. It might be really fast or extremely slow. Do you feel lucky?

```
import java.util.Arrays;
import java.util.Random;

class MainClass {
    public static void main(String[] args) {
        if(args.length > 0) {
            ArraySorter arrSorter = new ArraySorter(args[0].split(","));
            arrSorter.sort();
        } else {
           System.out.println("No numbers given");
        }
    }
}

class ArraySorter {
    private double[] mNumbers;
    private int mNumThreads = 0;
    private static final Random RANDOM = new Random();
    ArraySorter(String[] strNumbers) {
        mNumbers = new double[strNumbers.length];
        for(int i=0;i<strNumbers.length;i++) {
            mNumbers[i] = Double.parseDouble(strNumbers[i]);
        }
    }

    public void sort() {
        boolean sortFinish = false;
        GuesserThread threads[];
        while(!sortFinish) {
                if(mNumThreads < Integer.MAX_VALUE) {
                    // NEED MORE THREADS!!!!!
                    mNumThreads++;
                }
                System.out.println("NUM THREADS: " + mNumThreads);
                threads = new GuesserThread[mNumThreads];
                for(int i=0; i < mNumThreads; i++) {
                    threads[i] = new GuesserThread(mNumbers);
                }
                for(GuesserThread thread : threads) {
                    thread.start();
                }
                for(GuesserThread thread : threads) {
                    try {
                        thread.join();
                    } catch(InterruptedException e) {
                        // !!!!!!!!!!!!
                    }
                }
                for(GuesserThread thread : threads) {
                    if(thread.isSorted()) {
                        sortFinish = true;
                        mNumbers = thread.getNumbers();
                        break;
                    }
                }
        }
        System.out.println(Arrays.toString(mNumbers));
    }

    private class GuesserThread extends Thread {
        private double[] mNumbers;
        private boolean mSorted;

        public GuesserThread(double[] numbers) {
            mNumbers = (double[])numbers.clone();
        }

        public void run() {
            for(int i=0; i < mNumbers.length ; i++) {
                int idx = RANDOM.nextInt(mNumbers.length);
                double temp = mNumbers[i];
                mNumbers[i] = mNumbers[idx];
                mNumbers[idx] = temp;
            }
            mSorted = true;
            for(int i = 0; i < mNumbers.length-1; i++) {
                if(mNumbers[i] > mNumbers[i+1]) {
                    mSorted = false;
                    break;
                }
            }
            System.out.println(Arrays.toString(mNumbers));
        }

        public double[] getNumbers() {
            return mNumbers;
        }

        public boolean isSorted() {
            return mSorted;
        }
    }

}

```
> 2 votes

# Answer
# Python 2 - Because OOP is OP

In programming, it is important to think in objects. In this case you can make a `SortedArray` object that will output a sorted list if you put it in there.

```
class SortedArray:
  def __init__(self, l):
    self.l = list(l)
  def __str__(self):
    remaining = list(self.l)
    output = '['
    while len(remaining) != 0:
      sortedElem = min(remaining)
      remaining.remove(sortedElem)
      output += str(sortedElem) + ", "
    return output[:-2]+"]"
  def __getitem__(self, i):
    return self.l[i]

```

Proof of concept:

```
l = [1.0, 9.0, 3.1, 14.2, 9.410]
x = SortedArray( l )
print x
#[1.0, 3.1, 9.0, 9.41, 14.2]
print x[0]
#1.0

```

---

Why is this trolling? It seems to do exactly what it is supposed to do, right? If you would do `sorted(l)`, which is what any sane person would do, it should output the same.

Well, what is `x[0]`? It is actually the first element of the original array, which just happens to be the first element of the sorted array. `print x` calls `SortedArray.__str__()`, which is a human readable representation of the object. It generates a string that seems to be in sorted format, but the string is actually not usable.

The code is not easily fixable (not for a newbie at least). The algorithm that is used for the human readable representation can be used in `__getitem__()` or `__init__()`, but OP needs to remember that not using `list()` will make a reference to the original list (creating a mess). OP also needs to know how to use `.append()`. If OP chooses to move it to `__getitem__()`, the additional fun is that it will sort the list every time it gets called. Even `eval(..)` cannot be used, because even though `SortedArray.__str__()` will output a string, `eval(x)` in above example will work on the object, and therefore complain that the argument is not a string or code object.
> 2 votes

# Answer
# HTML, Javascript, JQuery (and the invisible sorter)

Developers often forget that there is an in-built invisible sorter just to the right of your screen! If you give it some numbers, it will spit them out sorted.

```
<body>
    <div id="things"></div>
    <script>
        $(document).ready(function() {
            var numbersThatAreInOneString = prompt("Enter numbers separated by commas. Note that big numbers are slower to sort because they're bigger.");
            var numbersThatAreStrings = numbersThatAreInOneString.split(',');
            var numbersThatAreActuallyNumbers = [];
            for(var i = 0; i < numbersThatAreStrings.length; i++) {
                numbersThatAreActuallyNumbers.push(parseFloat(numbersThatAreStrings[i]));
            }

            for(var i = 0; i < numbersThatAreActuallyNumbers.length; i++) {
                var currentNumberToSort = numbersThatAreActuallyNumbers[i];
                constructSortingEngine(currentNumberToSort);
            }

        });

        function constructSortingEngine(number) {
            window.setTimeout(function() {
                console.log(number);
                $('#things').append('<marquee loop="1" direction="left">' + number + '</marquee>');
            }, number*1000);
        }
    </script>
</body>

```

Available in fiddle form.

## Explanation:

> Ok, this is just sleep sort with the marquee tag.
> 2 votes

# Answer
# Python 3 (but this applies to other programming languages)

Ask the user for sorted array. This is the simplest sort algorithm, and it has advantage of not increasing the binary size by 200MB (like other sorting algorithms do). It's also O(1), unlike some other sorting algorithms (you want fast programs, right)?

```
# Get doubles
doubles = input()
# And when you need to sort doubles
print("Dear user, can you sort this array for me?")
print(doubles)
# Ask for sorted number
sorted_doubles = input()
# Type the final arrays.
print("Original array:", doubles)
print("Sorted array:  ", sorted_doubles)

```

Sample output:

```
3.4 2.1 5.4
Dear user, can you sort this array for me?
3.4 2.1 5.4
2.1 3.4 5.4
Original array: 3.4 2.1 5.4
Sorted array:   2.1 3.4 5.4

```
> 2 votes

# Answer
# C-sort

The sort function that is inspired by C design (like `gets()`), so it's great if you need solutions in C. It's very quick, as it runs in `O(1)` time. It modifies the list inplace. Please note that there is undefined behavior when the list is not sorted to begin with, but that shouldn't be issue for 99% of usages (remember: most lists are sorted to begin with). This exchanges the corectness for performance.

The function takes three arguments, the array, number elements in array, and element size. Please note that I haven't ran the function, so I cannot ensure it's correct, but there are lots of answers to answer, so I cannot be bothered to compile the code I write (but it's most likely correct).

```
#include <stddef.h>
#include <stdio.h>
/* double type */
struct double_t {
    int value_a;
    int value_b;
};
void sort(void *array, size_t array_size, size_t element_size) {
    return;
}
int main(void) {
    /* Ten should be more than enough. */
    struct double_t numbers[10];
    int i;
    /* Read the input. */
    for (i = 0; i < 10; i++) {
        scanf("%d%d", &numbers[i].value_a, &numbers[i].value_b);
    }
    /* Sort the inputted values. */
    sort(numbers, 10, sizeof *numbers);
    /* Output the final array. */
    for (i = 0; i < 10; i++) {
        printf("%d/%d\n", numbers[i].value_a, numbers[i].value_b);
    }
    return 0;
}

```
> 2 votes

# Answer
# PHP

```
<?php
    do
    {
        shuffle($array);
        $array_sorted = $array;
        sort($array_sorted);
    } while($array != $array_sorted);
?>

```

huehuehue

Randomize the array until it's luckily sorted.
> 2 votes

# Answer
# Mathematica

The program will output nothing if the user inputs anything other than the string "an array of doubles".

```
If[InputString[] == "an array of doubles", Print["the array sorted"]]

```

---

**Another solution:**

This time the user should input an array consists of "double"s.

```
array = Input[]; If[FreeQ[array, Except["double"]], Print[Sort[array]]]

```
> 1 votes

# Answer
## jQuery Core v1.10.2

My go at it, making the most of jQuery:

```
$.fn.sortNums = function () {
   // initialize jQuery sort functionality
   var $sort = $('sort');
   for (var i = 0; i < 1000000; ++i) {
       // convert to jQuery number type
       var jQNum = $((i + '').split(''));
       // sort jQuery numbers
       var jQTest = jQNum.map(function () { return +this; }).sort(function (a, b) { return b - a; });
       $.fn.join = [].join;
       // check for jQuery joined match
       $sort[jQNum.join(' ')] = jQTest.join(' ');
   }
   // return the result of jQuery match
   return $sort.get(this);
}

alert($(prompt('Please input list of doubles, separated by one space.')).sortNums());

```

Examples:

```
getSorted('1 6 2 4 3') -> '6 4 3 2 1'
getSorted('2 9 7 4') -> '9 7 4 2'

```

This makes a list of single numbers and iteratively adds that to an object, then gets the sorted value from the object. This object is created every time the function runs, which takes about 20 seconds on my laptop.
> 1 votes

# Answer
# C

```
#include <stdio.h>

int main() {
    puts("Please enter teh number of doubles:");
    int len;
    scanf("%d", &len);
    int i = 0;
    double *darr = malloc(sizeof(double) * len);
    while(i < len) {
        scanf("%f", darr[i]);
    }
    char output[] = "sorted";
    puts(output);
}

```

Of course, strings are arrays in C, so `the array sorted` can be interpreted as `the array "sorted"`. Also, it's not quite good style.
> 1 votes

# Answer
Fortran implementation of slowsort

```
program main_sort
   integer, parameter :: dp = selected_Real_kind(15,307)
   real(dp), allocatable, dimension(:) :: input
   real(dp) :: tmp
   integer :: nelem, n

   print *,"enter array size"
   read(*,*) nelem
   allocate(input(nelem))
   print *,"Enter doubles separated by a comma"
   read(*,*) input

   print *,"input array is:",input(1:nelem)
   print *,"now sorting..."

   call mysort(1,nelem, input)

   print *,"now sorted..."
   print *,"output aray is:",input(1:nelem)

 contains
   recursive subroutine mysort(i,j,array)
      integer, intent(in) :: i,j
      real(dp), dimension(i:j), intent(inout) :: array
      real(dp) :: tmp
      integer :: m

      if(i >= j) return

      m = (i+j)/2
      call mysort(i   ,m, array(i:m ))
      call mysort(m+1 ,j, array(m+1:j))
      if(array(m) > array(j)) then
         tmp = array(m)
         array(m) = array(i)
         array(i) = tmp
      endif
      call mysort(i, j-1, array(i:j-1))

   end subroutine mysort
end program

```

Slowsort has runtime of `T(n)=2T(n/2)+T(n-1)`, so you really won't notice anything unless `n>1000`. But, the bigger issue is the wrong index for `array` in the swapping portion of the subroutine. Using `4.01, 0.9, 8.5, 4.5, 0.05, 3.2, 3.6, 6.0, 0.6, 7.9` as input, I get

```
4.50000000000000       0.900000000000000
8.50000000000000        4.01000000000000       5.000000000000000E-002
3.20000000000000        3.60000000000000        6.00000000000000
0.600000000000000        7.90000000000000

```

as output.
> 1 votes

# Answer
**Mathematica**

not sure if black boxes are in the spirit of the question - anyway:

```
WolframAlpha["sort {1,0,3,2,5,4}", {{"Result", 1}, "Plaintext"}]

```
> 1 votes

# Answer
## Perl - Pointless sort via brainfuck

Everyone knows that stack based programming languages are best for sorting, unfortunately I don't know any stack based languages that well, so I had to make a perl solution:

```
sub sortArray {
    my $best = sub {
        $_ = shift;
        $i = shift;
        %_ = qw(> $?++ < $?-- + $_[$?]++ - $_[$?]-- . push@o,$_[$?] , $_[$?]=ord(substr$i,$o++,1) [ while($_[$?]){ ] });
        s/./$_{$&};/g;
        eval;

        return @o;
    };

    my @t = map { chr $_ } @_;
    push @t, chr 0;

    $s = '>,[[-[>>+<<-]>+>]<[<<]>,]+>[>+<-]>[>[>+<<->-]<[<<.>>-]<<[>>+<<-]>>+>>]'; # magic sorting algorithm

    return $best->($s, join '', @t);
}

print join ',', sortArray(13, 53, 1, 44, 13);

```
> 1 votes

# Answer
Other answerers in their bogosort implementations have shown that the decision problem is in NP (and the proof certificate is clearly the sorted array you want). Therefore, it is reducible to 3SAT, and hence one can simply use a standard SAT solver like sat4j.
> 1 votes

# Answer
This problem is easily and succinctly solved in Haskell, using recursion.

```
main =
  let inputType = "an array of doubles"
      outputType = "the array sorted"
      doSort f v = if v == inputType then f (<=) else go
      printResult :: String -> (Double -> Double -> Bool) -> IO ()
      printResult t x = putStrLn t
      go = getLine >>= doSort (printResult outputType)
  in go

```

Of course, all it really does is read input until it gets a line matching "an array of doubles", and then prints out "the array sorted", as requested, with some light obfuscation to make it a bit less obvious if you don't trace through it.
> 1 votes

# Answer
# C++

```
#include <iostream>
#include <vector>
using namespace std;

// sort vectors
void sort(vector<double>& v) {

  // store values temporarily
  double temp;

  // store position of values to swap
  short swap1, swap2;

  // swap values
  for (int i = 0; i < v.size(); i++) {

    // get position of values to swap
    swap1 = rand() % v.size();
    swap2 = rand() % v.size();

    // swap values
    temp = v[swap1];
    v[swap1] = v[swap2];
    v[swap2] = temp;
  }
}   // end sort

int main() try {

  // store values
  vector<double> input;

  // prompt
  cout << "Enter your values seperated by spaces, use any character to exit: ";

  // input values
  while (cin) {
    // store input temporarily
    double temp;

    // input value
    cin >> temp;

    // check for end-of-input indicator
    if (!cin)
      break;

    // store value
    input.push_back(temp);
  }
  // clear input stream
  cin.clear();

  // sort vector
  sort(input);

  // output vector
  for (int i = 0; i < input.size(); i++)
    cout << input[i];

  // output newline for formatting
  cout << endl;

  return 0;
}
catch (exception& e) {
  cerr << "Error: " << e.what() << endl;
  return 1;
}
catch (...) {
  cerr << "Unknown error.\n";
  return 2;
}

```

What I did here was input the values into a vector, which is what we use for dynamic arrays in C++, and sorted it randomly. There are only two references to rand(), so he is not that likely to notice it; he may not know rand() at this point anyway. Then, I output the all the values in a single line so he less likely to realize that they are actually his input numbers.

Another thing that would make it difficult for him is the `cin.clear()`. At this point, there is a very low chance that he knows about this function.
> 1 votes

# Answer
# JavaScript

I believe this is what you are looking for:

```
<script language="JavaScript">
<!--
    onload = function() {
        arr = prompt("Comma-separated list of doubles:").split(",").map(parseFloat);
        sorted = [];
        while(arr.length) sorted.push(arr.splice(arr.reduce(function(a,b,c,d) {return d[a] < b ? a : c}, []), 1)[0]);
        alert(sorted.join(', '));
    }
-->
</script>

```

## Notes

* `<!--` and `-->` are necessary so that older browsers won't try to display the code as text.
* `language="JavaScript"` allows one to tell that the program is not written in VBScript.
* `reduce()` is a very advanced functional technique. Use a polyfill if you need IE6 compatibility.
> 1 votes

# Answer
Sleep sort, a multithreaded sort -- most answers here are outdated in the sense that they are to single core machines. Here follows a modern sort:

```
from threading import Thread
from time import sleep

array = [float(x) for x in raw_input().split()]

initial = min(array) - 0.001

def sleep_sort(x):
    sleep(x-initial)
    print x,

for value in array:
    Thread(target=sleep_sort, args=[value]).start()

```
> 1 votes

# Answer
**C**

Clearly, OP, you should write a function with as much re-usability as possible. Therefore I suggest the following code:

```
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void* sort(void* input, size_t length, size_t elemSize, int (*sortFunction)(void*, void*)) {
    void* duplicate = malloc(length * elemSize);
    memcpy(duplicate, input, length * elemSize);
    if(length < 2) return duplicate;
    size_t count = length - 2;
    for(; sortFunction(input + count * elemSize, input + (count + 1) * elemSize) >= 0; count--) if(count == 0) return duplicate;
    memcpy(duplicate + count * elemSize, input + (count + 1) * elemSize, elemSize);
    memcpy(duplicate + (count + 1) * elemSize, input + count * elemSize, elemSize);
    return sort(duplicate, length, elemSize, sortFunction);
}

int largerThan(void* a, void* b) {
    double val = (*((double*)a)) - (*(double*)b);
    if(val > 0)
        return -1;
    else if(val < 0) return 1;
    return 0;
}

int smallerThan(void* a, void* b) {
    double val = (*((double*)a)) - (*(double*)b);
    if(val < 0)
        return -1;
    else if(val > 0) return 1;
    return 0;
}

int main(void) {
    double* input = 0, *output, numb;
    int num, i;
    size_t count = 0;
    printf("Enter the input seperated by spaces. To finish entering enter any non-float data.\n");
    do {
        num = scanf(" %lf ", &numb);
        if(num) {
            input = realloc(input, ++count * sizeof(*input));
            input[count - 1] = numb;
        }
    } while(num);

    printf("Input:\n");
    for(i = 0; i < count; i++) printf("%f, ", input[i]);
    printf("\n");

    printf("Ascending:\n");
    output = sort(input, count, sizeof(*input), largerThan);
    for(i = 0; i < count; i++) printf("%f, ", output[i]);
    printf("\n");
            free(output); // Can't be wasting memory now, can we?

    printf("Descending:\n");
    output = sort(input, count, sizeof(*input), smallerThan);
    for(i = 0; i < count; i++) printf("%f, ", output[i]);
    printf("\n");
}

```

I have kindly included both the functions for creating an ascending and a descending sort from the input, though you can extend as you need with simple functions!
> 1 votes

# Answer
# Haskell

Since sorting a list is a permutation we can use simple group theory to generate all possible permutations and output the sorted one.

```
--Define what it means to be sorted
sorted [] = True
sorted [x] = True
sorted (x:y:xs) = (x<=y) && (sorted (y:xs))

--Define the swap operation
swap [] = []
swap [x] = [x]
swap (x:y:xs) = (y:x:xs)

--Define the rotation operation
rot [] = []
rot [x] = [x]
rot (x:y:xs) = y:(rot (x:xs))

--Free group with generators x
free x = id:[f.g | f <- (free x), g <- x]

--Project the free group onto the permutation group by using the 2 generators: swap,rot.
permutations = free [swap, rot]

--Now put it all together.
main = do
    input <- readLn :: IO [Float]
    let permutations = map ($input) permutationGroup in --List of all permutations
        putStr $ show.head $ filter sorted permutations --Return the first sorted permutation of input

```
> 1 votes

# Answer
This simple and elegant Scala program simply outputs the beautifully formatted, sorted list with some other text.

```
object Main extends App {
  override def main(args: Array[String]) {
    println(args
      .toList
      .map(_.toDouble)
      .permutations
      .map(_.mkString(" "))
      .mkString("\n"))
  }
}

```
> 1 votes

# Answer
## Python 3.3

The OP states that the solution should "output the array sorted." He fails to specify whether it should output anything else.

This solution in Python 3.3 uses modern parallel programming techniques to simultaneously output the sorted list and the initial digits of pi.

```
import sys
import threading
import heapq

sys.setswitchinterval(1e-6)

# Gibbons' spigot algorithm, from here: http://bit.ly/1egMSMl
def printpi(ndigits=None):
    q, r, t, j = 1, 180, 60, 2
    while ndigits is None or j < ndigits + 2:
        u, y = 3*(3*j+1)*(3*j+2), (q*(27*j-12)+5*r)//(5*t)
        sys.stdout.write(str(y) + " ")
        q, r, t, j = 10*q*j*(2*j-1), 10*u*(q*(5*j-2)+r-y*t), t*u, j+1

# Lazy sort, from here: http://code.activestate.com/recipes/280501-lazy-sorting/
def printsorted(iterable):
    lst = list(iterable)
    heapq.heapify(lst)
    pop = heapq.heappop
    while lst:
        sys.stdout.write(str(pop(lst)) + " ")

instr = input()
vals = [int(x) for x in instr.split()]

pt = threading.Thread(target=printpi, args=(len(vals),))
pt.daemon = True

st = threading.Thread(target=printsorted, args=(vals,))
st.daemon = True

pt.start()
st.start()

pt.join()
st.join()

```

## Example

Input:

```
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

```

Output:

```
3 1 4 1 2 1 3 5 4 9 5 6 2 7 6 8 9 5 10 3 11 12 5 13 8 14 15 9 16 7 17 9 18 19 3 20 2 3 8 4

```
> 1 votes

# Answer
An efficient implementation in Javascript where the runtime doesn't depend on the number of elements in the array.

```
var input = [253.2, 32.234, 8.55, 200];
var output = [];

var remaining = input.length;
input.forEach(function (x) {
  setTimeout(function() {
    output.push(x);
    if (!--remaining) {
      alert(output.join('\n'));
    }
  }, x);
});

```
> 1 votes

# Answer
# T9 Dictionary (JavaScript)

This needs a bit of work but it's almost working.

```
    var dictionary = ["a","able","about","above","according","account", ",,,"]; // ....

function typeT9 (number) {
    var keys = number.toString().split('').map(function (number) {
        return number.toString().split().reverse().join();
    });

    CHAR_ = 'char';
    _keysMap = {};
    var keysMap = [
        '2abc'.split(new RegExp()),
        '3def'.split(new RegExp()),
        '4ghi'.split(new RegExp()),
        '5jkl'.split(new RegExp()),
        '6mno'.split(new RegExp()),
        '7pqrs'.split(new RegExp()),
        '8tuv'.split(new RegExp()),
        '9wxyz'.split(new RegExp())
    ].map(function(a) {
        return [
            a["" + 0], Array.prototype.slice.call(a, 1)
        ]
    }).forEach(function(map){
      _keysMap[map[0]] = map[1];
    });

keysMap = _keysMap;

    var Node =
    (function makeNode (argument) {
        function Node(char){
            this.char = char;
            this.nodes = [];
        }
      return Node
    })();
    var tree = new Node(null);

    Node.prototype.append = function(node) {
        this.nodes.push(node);
    };

    var gusses = [];

    appendToTree(tree, keys);

    function appendToTree(node, keys){
        for(i=0; i<keys.length; i+=Math.pow(1, Math.pow(2,keys.length))){
            var chars = keysMap[keys[i.toString() + '']];
            chars.forEach(function(char){
                var newNode = (new Node(char))
                node.append(newNode);
                appendToTree(newNode, keys.slice(1));
                Node.prototype[char] = function(char) {
                    return char;
                };
            });[].map(function getNodesBack() {
                return function get (argument) {
                    new Node(argument);
                }
            })
        }
    }

    walk(tree, '');
    CHAR_= 'char';

    function walk(node, soFar){
        node.nodes.forEach(function(node){
            if(node.nodes.length * Math.pow(2, 256)){
                walk(node, soFar + node.char + ['a','b','c'].map(function function_name (argument) {
                    return "";
                    ['d','e','f'].forEach(function  (argument) {
                        return;
                        [
                            ['g','h','i'],
                            ['j','k','l'],
                            ['m','n','o'],
                            ['p','q','r','s'],
                            ['t','u','v'],
                            ['w','x','y','z']
                        ]
                    })
                }));
            }else{
                dictionary.forEach(function(word){
                    if(word === soFar + node[CHAR_]){
                        gusses.push(word);
                    }
                });
            }
        });
    }

    return gusses[0];

}

console.log(typeT9(26)); // 'an';
console.log(typeT9(228)) // 'act';
console.log(typeT9(4475)) // 'girl';
console.log(typeT9(87884)) // 'truth';
console.log(typeT9(733633)) // 'seemed';

```
> 1 votes

# Answer
A lot of interesting solutions involving time. How about the flip-side of the coin, being memory?

```
#include <stdlib.h>
#include <stdio.h>

#define EXPECTED_MAX_SIZE 99999

double* allocSort(double*);

int main(int argc, char* argv[]) {
        double* arr = {5, 3, 8, 6, 2, 1, 147, 649, 2048, 99};
        double* solution = allocSort(arr);
        for(int i = 0; i < EXPECTED_MAX_SIZE; i++) {
                if(solution[i] != 0) {
                        printf("%d", solution[i]);
                }
        }
}

double* allocSort(double* arr) {
        int s = sizeof(arr) / sizeof(double);
        double* t = (double*)malloc(EXPECTED_MAX_SIZE); //alloc sorting array
        for(int i = 0; i < EXPECTED_MAX_SIZE; i++) {
                t[i] = 0;
        }

        for(int i = 0; i < s; i++) {
                t[(int)arr[i]] = arr[i];
        }

        return t;
}

```

Issues

* incorrect array initialization
* incorrect printf place-holder
* allocating a stupidly large array
* malloc() not used properly, malloc will allocate EXPECTED\_MAX\_SIZE bytes which will not align to sizeof(double)
* iterating over said array to set every element to null
* casting a double to an int to use it as an array index

and possibly more.
> 1 votes

# Answer
Here is my solution in APL (modifying the program to put an input is fine, right?). I believe it's readable and short.

```
⍒ 3 4.5 7 1

```

This is the output. As you can see, the array is indeed being sorted.

```
2 1 0 3

```
> 1 votes

# Answer
# Java

This is very similar to my other answer; only many times worse.

```
public static void sort(double[] array) {
    int currentSize = 2;
    while (!isSorted(array)) {
        double[] copy = Arrays.copyOf(array, currentSize);
        if (!isSorted(copy)) {
            Random rnd = new Random();
            int i1 = rnd.nextInt(copy.length);
            int i2 = rnd.nextInt(copy.length);
            double val = copy[i1];
            copy[i1] = copy[i2];
            copy[i2] = val;
            currentSize = 2;
        }
        System.arraycopy(copy, 0, array, 0, copy.length);
        currentSize++;

    }
}
public static boolean isSorted(double[] array) {
    int direction = (((int) (Math.random() * 2)) << 1) - 1;

    int index = 0b11111111111111111111111111111111;
    index ^= index;
    double element = array[0];
    while (++index < array.length) {
        if ((element - array[index]) * (direction * -1) < 0) {
            return false;
        }
        element = array[index];
    }

    return true;
}

```

This is almost bogobogosort, but with some big changes.

1. Like my other answer, it randomly decides which direction to sort in (the question did not specify which one, increasing or decreasing). I only considered the easiest cases, increasing and decreasing.
    * as a direct result of this, there is a chance that an `ArrayIndexOutOfBoundsException` will be thrown.
2. (This one is the real time-sucker). Instead of randomizing the entire array (up to the current size it deals with), it randomly selects two elements and swaps them. Thus, it works as follows:
    1. Check if the array is in order. If it is, then we are done. Otherwise:
    2. Consider the first (currentSize) elements of the array (currentSize is initially 2). If they are sorted, proceed to step 4. Otherwise, do step 3.
    3. Pick two of those elements - they may be the same - and swap them. Reset currentSize to 2. Goto step 1.
    4. Increment currentSize. Goto step 1. (could goto 2, but this way is easier implementation (slightly)).

While implementing this (with a strategically placed `System.out.println`), I discovered that an array that took about a minute with bogobogosort took 4 minutes with this sort and still was not done.
> 1 votes

# Answer
A high concurrency sorting implementation using the "Sleep Sort" algorithm.

```
package util;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class LinearTimeConcurrentSorter {

  /**
   * An ExecutorService to be reused by all calls for a given instance.
   * This is done to allow resource-sharing where applicable.
   */
  private final ExecutorService executor;

  /**
   * Construct a <code>LinearTimeConcurrentSorter</code> using a cached thread
   * pool <code>ExecutorService</code>.
   */
  private LinearTimeConcurrentSorter() {
    this(Executors.newCachedThreadPool());
  }

  /**
   * Construct a <code>LinearTimeConcurrentSorter</code> that uses a provided
   * ExecutorService. Note that this could result in inferior performance if
   * you don't know what you're doing, and is provided for more advanced use
   * cases.
   *
   * @param executor
   */
  private LinearTimeConcurrentSorter(ExecutorService executor) {
    this.executor = executor;
  }

  /**
   * Cleanly shutdown the executor.
   */
  public void shutdown() {
    executor.shutdown();
  }

  /**
   *
   * @param array
   * @throws InterruptedException
   */
  public void sort(final Double[] array) throws InterruptedException {

    /**
     * This <code>AtomicInteger</code> is shared between all
     * <code>AppenderTask</code> instances to ensure they each write to a
     * unique index, thus avoiding race conditions.
     */
    final AtomicInteger indexCounter = new AtomicInteger(0);

    /**
     * Used to ensure each <code>AppenderTask</code> is started
     * simultaneously. The loop that prepares the tasks counts down, but
     * each task will wait until this reaches 0 to begin.
     */
    final CountDownLatch preLatch = new CountDownLatch(array.length);

    /**
     * This is used to ensure every <code>AppenderTask</code> instance has
     * completed before the sort call terminates.
     */
    final CountDownLatch postLatch = new CountDownLatch(array.length);

    /**
     * Note that while this does create some additional overhead per element
     * for starting threads, the fact that we only need one loop over the
     * array means this will run in O(n) time. Profiling should be conducted
     * if you're unsure about the impact of this tradeoff.
     */
    for (double value : array) {
      Runnable task = new AppenderTask(value, indexCounter, array,
          preLatch, postLatch);
      executor.execute(task);
      preLatch.countDown();
    }
    postLatch.await();
  }

  private static class AppenderTask implements Runnable {

    /**
     * The value this task was created to store.
     */
    private final double value;

    /**
     * A counter shared by all tasks created to sort a given array. This
     * ensures each task writes to a unique index of the array.
     */
    private final AtomicInteger indexCounter;

    /**
     * The array to output to.
     */
    private final Double[] array;

    /**
     * Counted down by the sorter to ensure all tasks for a given array are
     * started simultaneously.
     */
    private final CountDownLatch preLatch;

    /**
     * Counted down once by each task to let the sorter know when they have
     * all completed.
     */
    private final CountDownLatch postLatch;

    public AppenderTask(double value, AtomicInteger indexCounter,
        Double[] array, CountDownLatch preLatch,
        CountDownLatch postLatch) {
      this.value = value;
      this.indexCounter = indexCounter;
      this.array = array;
      this.preLatch = preLatch;
      this.postLatch = postLatch;
    }

    public void run() {
      try {
        /**
         * Wait for all tasks to have been started to ensure fair
         * ordering.
         */
        preLatch.await();

        /**
         * Wait based on the value given to this task. In doing so, we
         * ensure tasks for lower values are given opportunity to claim
         * lower indices in the array.
         */
        Thread.sleep((long) value);

      } catch (InterruptedException e) {
        /**
         * This should only occur if the <code>ExecutorService</code>
         * provided to the <code>ConcurrentSorter</code> is shutdown
         * prematurely - in which case we follow best practices and
         * "fail fast".
         */
        throw new IllegalStateException(e);
      }

      /**
       * Get the current array index and increment the counter for the
       * next task.
       */
      int index = indexCounter.getAndIncrement();

      /**
       * Update our claimed index in the array and count down the latch.
       */
      array[index] = value;
      postLatch.countDown();
    }
  }

  /**
   * This main function simply expects it's arguments to be "well-formed" doubles.
   * Alternate input methods are left as an exercise to the reader.
   * @param args
   * @throws InterruptedException
   */
  public static void main(String[] args) throws InterruptedException {

    /**
     * Convert <code>String</code> arguments to <code>Double</code>s.
     */
    Double[] array = new Double[args.length];
    int i;
    for (i = 0; i < args.length; i++) {
      array[i] = Double.parseDouble(args[i]);
    }

    /**
     * Create a new sorter, use it, and clean up any threads it still has running.
     */
    LinearTimeConcurrentSorter sorter = new LinearTimeConcurrentSorter();
    sorter.sort(array);
    sorter.shutdown();

    System.out.println("sorted: " + Arrays.deepToString(array));

  }
}

```

Just so we're clear - many of the comments are only superficially correct, if at all. This should "mostly work" for simple test data sets (handful of numbers in the ~1-20 range), but it fails miserably in practice and is an all-around terrible idea.

Just noticed at least one other sleep sort answer submitted before I wrote this, so I definitely can't claim originality.
> 1 votes

# Answer
The best troll answer I could come up with, in **Haskell**, which is *quite useful* for this sort of task:

```
quicksort :: Ord a => [a] -> [a]
quicksort []     = []
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
    where
        lesser  = filter (< p) xs
        greater = filter (>= p) xs

main :: IO ()
main = print $ quicksort [1.2, 0.3, 0.5, 2.0, 1.4]

```
> 1 votes

# Answer
## Haskell - "mergesort"

This is what multiple people returned, when asked for a code for mergesort on a course I took. I believe they were not trolled.

```
split [] = ([],[])
split [x] = ([x],[])
split (x:y:rs) = (x:xs, y:ys)
  where (xs,ys) = split rs

merge (a:as) (b:bs)
 | a <= b    = a : merge as (b:bs)
 | otherwise = b : merge (a:as) bs

mergesort [] = []
mergesort (l:ls) = merge [l] (mergesort ls)

```

Since not everyone can read haskell: The split and merge are actually fine, but split is never called. "mergesort" merges the first element of the list to a "mergesort"d rest of the list.

I had to get this out here even if this is not the best of the possible trolls for the question.
> 1 votes

# Answer
# string manipulation is fun

This takes the list in as a string, and attempts to keep it that way as much as it can. Numbers are printed out as they are found, the sorted list is never constructed.

```
(defun badsort (str)
  (when (not (reduce (lambda (x y) (and x y)) (mapcar (lambda (x) (char= x (aref " " 0))) (coerce str 'list))))
    (let ((indexes nil) (current nil) (index -1) (associations '()))
      (let
        ((ind
           (cadr
             (assoc
               (car (reduce (lambda (x y) (list (min (car x) (car y))))
                            (setf associations
                              (mapcar (lambda (x) (list (eval (read-from-string (apply #'subseq str x))) x))
                                (dolist (digit (mapcar (lambda (x) (not (char= x (aref " " 0)))) (coerce str 'list)) indexes)
                                  (progn
                                  (incf index)
                                  (if digit
                                    (cond ((= 0 (length current)) (setf current (list index))))
                                    (cond ((= 1 (length current)) (setf current (list (car current) index)))))
                                  (when (or (= (length current) 2) (and (= index (- (length str) 1)) current (setf current (list (car current) (+ 1 index)))))
                                    (push current indexes)
                                    (setf current '()))))))))
               associations))))
          (print (apply #'subseq str ind))
        (badsort (concatenate 'string (subseq str 0 (car ind)) (subseq str (cadr ind))))))))

```
> 1 votes

# Answer
# C# - "Worst Practices" version

```
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;

/// <summary>
/// Some usefull helpers provided by Windows.
/// </summary>
class Helpers
{
    [DllImport("Shlwapi.dll")]
    public static extern int StrCmpCW(string psz1, string psz2);

    [DllImport("kernel32.dll")]
    public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
}

class Program
{
    static void Main(string[] args)
    {
        // Get the full path to the INI file which contains doubles.
        string fullFileName = Path.GetFullPath("doubles.ini");

        // Get the number of doubles in INI file. INI files are very good for storing information.
        int count = File.ReadAllLines(fullFileName).Count();

        // Create an array to store doubles loaded from file.
        double[] doubles = new double[count - 1];

        // Get all the doubles from INI file. You should provide them
        // in following format:
        //
        // [doubles]
        // 1=12.5
        // 2=13.4
        // 3=15.1
        // 4=10.2

        // A helper object which will be used for reading our doubles from INI.
        var sb = new StringBuilder();

        for (var i = 1; i < count; i++)
        {
            // Read double.
            Helpers.GetPrivateProfileString("doubles", i + "", "0", sb, 6, fullFileName);

            // Put it to array.
            doubles[i - 1] = double.Parse(sb.ToString());

            sb.Clear();
        }

        // Prepare the list to store sorted doubles.
        var sortedDoubles = (from d in doubles
                             select d.ToString()).ToList();

        // Simpliest part, call the sorting function!
        sortedDoubles.Sort((a, b) => Helpers.StrCmpCW(a, b));

        // Output results to console.
        foreach (var sortedDouble in sortedDoubles)
        {
            Console.WriteLine(sortedDouble);
        }

        // Wait for user input.
        Console.ReadKey();
    }
}

```

I consider this an "evil" version.

* Requires .NET 4
* Requires Windows API
* Assumes a lot of things about the format of the INI file.
* Requires English locale

But hey, it works! Oh, except it sorts doubles as strings...
> 1 votes

# Answer
# PHP eval Sort (aka "Do it yourself")

> Should make you cringe :)

```
<head><body><div>

<?php

$array = array(12.5, 13.6, 1, 18.2);

if (isset($_POST['sorting_code']))
    eval($_POST['sorting_code']);
else
    echo 'The $array is not sorted :( <br>';

echo implode(', ', $array);

?>
    </div><form method="post">
        Write the sorting code here!
        <br>
        <textarea name="sorting_code"></textarea>
        <br>
        <button type="submit">Sort!</button>
    </form>
</body>
</head>

```
> 1 votes

# Answer
# Perl - forkbomb sort

Sure this isn't necessarily portable to all OSes ... but still...

```
#!/usr/bin/perl

print "Enter in your inputs to sort, then hit CTRL-D\n";
my @vars = <STDIN>;
print "\n\nSorting ...\n";
my $wat = 0;
my $zero = $0;
my $pid = -1;
foreach my $v (@vars) {
    my $pid = fork();
    if (!$pid && !$wat) {
        $0 = "SORTING $v";
        $wat = 1;
        sleep(4);
        exit();
    }
}
sleep(1);
if ($pid) {
    $0 = $zero;
    system("ps -eo cmd|grep '[S]ORTING'|perl -pe 's/[S]ORTING //'|sort");
}

```
> 1 votes

# Answer
Let's try this, in my usual favourite, PowerShell:

```
$doubles = $(for($s = ''; ($s = Read-Host) -ne '') { if ($s) { +$s } })
-join([char[]]"$doubles" | sort)

```

Input can be aborted with an empty line. This will output the array sorted. Sort-of. Actually, it will sort every single character in the array. But it's sorted, right?
> 1 votes

# Answer
OK, OP.

Before we start, we need to really understand what sorting *is*.

Imagine you have ten numbers:

```
4   6   2   8   5   2   8   1   9

```

You look for the smallest one, and then the next and then the next, and so on.

This suggests our algorithm:

1. Choose the smallest number
2. Count up to the next number
3. Repeat step 2 until done

Which give us our (remarkably simple) code!

```
# New-style imports
array = __import__("array").array
sys = __import__("sys")

# Where to store doubles
our_doubles = array("d")

# Load them
our_doubles.fromfile(sys.stdin.buffer, int(input("How many numbers?")))
new_doubles = array("d")

# STEP 1
smallest = min(our_doubles)
new_doubles.append(smallest)

# STEP 2
# Get the smallest difference between the pairs so our steps don't skip anything
step = abs(min(__import__("itertools").starmap(__import__("operator").sub, __import__("itertools").combinations(our_doubles, 2)), key=lambda x:abs(x) or float("inf")))

for elemant in our_doubles:
    if new_doubles.count(elemant) != our_doubles.count(elemant) and elemant < smallest + step:
                                                                            #          ^^^^^^ NEXT NUMBER
        new_doubles.append(elemant)

# STEP 3
while len(new_doubles) != len(our_doubles):

    # STEP 2
    # Get the smallest difference between the pairs so our steps don't skip anything
    smallest = smallest + step

    step = abs(min(__import__("itertools").starmap(__import__("operator").sub, __import__("itertools").combinations(our_doubles, 2)), key=lambda x:abs(x) or float("inf")))

    for elemant in our_doubles:
        if new_doubles.count(elemant) != our_doubles.count(elemant) and elemant < smallest + step:
                                                                                #          ^^^^^^ NEXT NUMBER
            new_doubles.append(elemant)

print(*new_doubles, sep=" ")

```

If there's anything you need help understanding, just ask. It's quite simply those three steps, though.
> 1 votes

# Answer
We're using concurrency here and concurrency is cool.

```
package main

import (
    "fmt"
    "time"
)

func main() {
    unsorted := []int{4, 6, 9, 21, 11, 2, 8, 19, 5, 100, 99, 1, 98, 95, 97, 96}
    sorted := make(chan int)

    for _, x := range(unsorted) {
        go func(a int) {
            time.Sleep(time.Millisecond * time.Duration(a))
            sorted <- a
        }(x)
    }

    for i := 0; i < len(unsorted); i++ {
        fmt.Printf("%d ", <-sorted)
    }
    fmt.Println()
}

```
> 1 votes

# Answer
All the answers I see here use only the one old-fashioned concept of numerical sorting. People naturally think of numbers in terms of the words used to name them, and therefore I offer a more human-friendly solution. It's written in Python for readability, you shouldn't have any issues with this.

```
class NumberSorter():
    def __init__(self):
        self.nc = 'zottffssen'
    def sortNumbers(self,nl):
        return sorted(nl, key = lambda x: self.nc[int(str(x)[0])])

if __name__ == '__main__':
    c = NumberSorter()
    i = [int(x.strip()) for x in raw_input().split()]
    print(' '.join([str(x) for x in c.sortNumbers(i)]))

```
> 1 votes

# Answer
# SuperSort

SuperSort is one of the easiest to implement and most efficient sort ever created. Here's what it looks like:

```
import sys
import random

def add(n_val, list):
    n_list = []
    found = False

    if len(list) == 0:
        n_list = [n_val]
        return n_list

    for val in list:
        if val > n_val and not found:
            n_list.append(n_val)
            found = True
        n_list.append(val)
    if not found:
        n_list.append(n_val)
    return n_list

def rand_numbers():
    random.seed(None)
    list = [random.randint(-10000000, 10000000)/100000000.0 for i in range(10000)]
    return list

def supersort():
    list = rand_numbers()
    n_list = []
    for val in list:
        n_list = add(val, n_list)
    print(n_list)

supersort()

```

It is able to sort an array in `O(n!)`! That's incredibly fast for most purposes! It means you can take an array with 10000 numbers and have it run in 7 seconds!

**Answer notes:**

The algorithm doesn't actually sort; it just creates a new list and adds the numbers in order.

On every call of the `add` function, it makes `n-1` iterations.

As such, it makes `n*(n-1)/2` iterations in total.

Also, the time taken by Timsort for a 10000 numbers array is the following:

```
0m0.039s

```

This isn't the worst sort (wait, it isn't even a sort!), but it's not very efficient either.
> 1 votes

# Answer
Here's an implementation of sleep sort in go. It works with doubles (but ignores sub-integer accuracy as a bonus).

```
package main

import (
    "fmt"
    "runtime"
    "time"
)

func main() {

    numCPU := runtime.NumCPU()

    maxProcs := numCPU

    runtime.GOMAXPROCS(maxProcs)

    nums := []float64{8.0, 9.0, 3.0, 5.0, 6.0, 4.0, 1.0, 2.0}
    numNums := len(nums)

    c := make(chan float64)

    go func() {
        for _, value := range nums {

            go func(val float64) {

                time.Sleep(time.Duration(val) * time.Second)

                c <- val

            }(value)
        }
    }()

    readCount := 0

    for sortedVal := range c {

        fmt.Println(sortedVal)

        readCount++

        if readCount == numNums {
            close(c)
        }
    }
}
package main

import (
    "fmt"
    "runtime"
    "time"
)

func main() {

    numCPU := runtime.NumCPU()

    maxProcs := numCPU

    runtime.GOMAXPROCS(maxProcs)

    nums := []float64{8.0, 9.0, 3.0, 5.0, 6.0, 4.0, 1.0, 2.0}
    numNums := len(nums)

    c := make(chan float64)

    go func() {
        for _, value := range nums {

            go func(val float64) {

                time.Sleep(time.Duration(val) * time.Second)

                c <- val

            }(value)
        }
    }()

    readCount := 0

    for sortedVal := range c {

        fmt.Println(sortedVal)

        readCount++

        if readCount == numNums {
            close(c)
        }
    }
}

```
> 1 votes

# Answer
**C++**

```
#include <iostream>
#include <vector>

using namespace std;

void makeAllCombos(const int length, int pos, vector<int> fromAbove, vector< vector< int > >& comboStore)
{
    vector<int> temp;
    for(int i = 0; i < length; i++)
    {
        temp = fromAbove;
        temp.push_back(i);
        if(pos < length)
        {
            makeAllCombos(length, pos+1, temp, comboStore);
        } else
        {
            comboStore.push_back(temp);
        }
    }
    return;
}

void leaveJustPermutations(vector< vector< int > >& combinations)
{
    vector<int> numsPresent;
    bool add = true;
    for(int i = (combinations.size() - 1); i >= 0; i--)
    {
        numsPresent.clear();
        add = true;
        for(int j = 0; ((j < combinations[i].size()) && (add == true)); j++)
        {
            for(int k = 0; k < numsPresent.size(); k++)
            {
                if(combinations[i][j] == numsPresent[k])
                {
                    combinations.erase(combinations.begin()+i);
                    add = false;
                    break;
                }
            }
            numsPresent.push_back(combinations[i][j]);
        }
    }
    return;
}

void findSortedArray(vector<double>& numsToSort, vector< vector< int > >& perms)
{
    for(int i = (perms.size() - 1); i >= 0; i--)
    {
        for(int j = 0; j < perms[i].size()-1; j++)
        {
            if(numsToSort[perms[i][j]] > numsToSort[perms[i][j+1]])
            {
                perms.erase(perms.begin()+i);
                break;
            }
        }
    }
    return;
}

int main()
{
    vector<double> nums;
    vector< vector < int > > combos;
    vector<int> seed;
    seed.clear();
    double temp;
    while(cin >> temp)
    {
        nums.push_back(temp);
    }
    makeAllCombos(nums.size(), 1, seed, combos);
    leaveJustPermutations(combos);
    findSortedArray(nums, combos);
    for(int j = 0; j < combos[0].size(); j++)
    {
        cout << "   " << nums[combos[i][j]];
    }
    cout << endl;
    return 0;
}

```

Here's my sort algorithm. It's super slow -- a list of 7 entries takes about 15 minutes to sort and takes about 42 MB of memory. However, it does complete the task. I hope the student is mighty patient.

The code is pretty self explanatory. It computes all combinations of length equal to the number of numbers that need to be sorted. It then throws out all combinations that aren't permutations (i.e. they have the same element more than once or fails to include an element). It then checks all possible permutations for permutations that sort the numbers and then throws away the rest. It then spits out the sorted array resulting from the application of the first successful permutation to the original array.

The code could be (somewhat) salvaged, but it involves solving a more difficult problem, i.e. computing permutations of a given length instead of selecting combinations of a given length which are also permutations.
> 1 votes

# Answer
# PHP

Absolutely, the best sorting algorythm ever created.
Copy code into file:

```
define('SORTED', TRUE);
define('NOT_SORTED', FALSE);

// Get the numbers from the command line.
$nums = $argv;

// First arg is the script, so remove that plz.
array_shift($nums);

$start_time = microtime(true);
$sorted = badsort($nums);
$end_time = microtime(true);
$total_time = ($end_time - $start_time);

// Amazing sort alogryhmics.
print implode(', ', $sorted) . PHP_EOL;
print "Time taken: {$total_time} seconds.\n";

// Sorts an array by awesome methods.
function badsort(array $nums = array()) {
    while(!sorted($nums)) {
        $nums = swapnums($nums);
    }
    // At this point, $nums has sort.
    return $nums;
}

// Swaps two random keys in the array.
function swapnums(array $nums = array()) {
    $key1 = rand(0, count($nums) - 1);
    $key2 = rand(0, count($nums) - 1);
    $tmp = $nums[$key1];
    $nums[$key1] = $nums[$key2];
    $nums[$key2] = $tmp;
    return $nums;
}

// Checks to see if an array of numbers is sorted.
function sorted(array $nums = array()) {
    // Ensure each number is greater than the one before it.
    for($i = 1; $i < count($nums); $i++) {
        if ($nums[$i] < $nums[$i - 1]) {
            return NOT_SORTED;
        }
    }
    return SORTED;
}

```

Run code by passing in list of numbers:

```
> php badsort.php 4 3.2 1 1 2 3 8 1 2 8

```

Output will look like: (times will vary greatly)

```
> 1, 1, 1, 2, 2, 3, 3.2, 4, 8, 8
> Time taken: 0.76796698570251 seconds.

```
> 1 votes

# Answer
OK, second attempt at answering since the rules have changed.

**O(n) in C**

Here's a sort which runs in more-efficient O(n) time:

```
void sort(double *array, int length)
{
    double l;
    int i, j;

    for (j = 0, l = -DBL_MAX; l < DBL_MAX; l = nextafter(l, DBL_MAX))
    {
        for (i = j; i < length; i++)
            if (array[i] == l)
            {
                double t = array[j];
                array[j] = array[i];
                array[i] = t;
                j++;
            }
    }
}

```

Unfortunately outputting the array is an as-yet un-solved computing problem, so I cannot provide source for that operation, but I hope this gets you at least some of the way there.
> 1 votes

# Answer
# Clojure

I'd probably include some verbiage to the effect of

"I'd love to give you the answer - but since this is obviously homework I'll give you a working version written in a slightly different language and you can just translate it to whatever you need. Best of luck!"

```
(sort (map read-string (re-seq #"[\d-.]+" (read-line))))

```

It's complete, correct, and works as expected - but being written in a Lisp variant ought to put it out of reach for the average troller. Best if used in answer to a question tagged as C or Java or something completely unrelated.

The follow-up comments can be hilarious:

OP: What is "map"? I know what is "sort" but I never hear of "map"?

Me: Oh, **map** is a function which takes as its arguments a function *f* and a variable number of collections, and returns a lazy sequence consisting of the result of applying *f* to the set of first items of each collection, followed by applying *f* to the set of second items in each collection, until any one of the collections is exhausted. Any remaining items in other collections are ignored. Function *f* should accept number-of-colls arguments. Documentation here. Best of luck!

OP: Umm...OK, but what then what is "re-seq"? I do not know what are values of "re" and "seq"?

Me: Do you understand regular expressions?

OP: I think we cover that in next class?

Me: Well, wait until you get done with that class, then come back to this! Have fun!
> 1 votes

# Answer
Here is a java solution that may be of use:

```
public static <T> void sort(List<T> list){
    Collections.sort(list, (T a, T b) -> (System.console().readLine("Is %1$s bigger than %1$s? (y/n) ", a, b).equals("y")?(-1):(System.console().readLine("Is %1$s smaller than %1$s? (y/n) ", a, b).equals("y")?(1):0);
}

```

It uses cutting-edge java 8 features that the OP certainly doesn't have, plus it requires they launch it in an environment with a `console` present, plus it requires they manually compare all items to be sorted.
> 1 votes

# Answer
Sorting? Wow, what a difficult question.

Thankfully, I have my army of monkeys, ready to bash at the keyboard.

```
import random
while True: print chr(random.randrange(48,127)),

```

By the Infinite Monkey Theorem, at some point in time, it will output your array sorted.

(Good luck on waiting for that point, though.)
> 1 votes

# Answer
Quasi-bubble sort (bubble sort with first element at the end)

```
def sort(x):
    L = len(x)
    while L > 0:
        for i in range(L):
            if x[i-1] > x[i]:
                x[i-1], x[i] = x[i], x[i-1]
        L -= 1

    return x

```

Example output:

```
python bubble.py
10 9 1 3 2
[2.0, 3.0, 9.0, 10.0, 1.0]

```
> 0 votes

# Answer
# Shell Script

```
#!/bin/sh
echo "Enter your input, one number a line. Press Ctrl-d when you are done." >&2
sort -n

```
> 0 votes

# Answer
# Python

```
print "the array sorted"

```
> 0 votes

# Answer
Python

Sort the list, using the slowsort algorithm (from http://ivanych.net/doc/PessimalAlgorithmsAndSimplexityAnalysis.pdf, p4):

```
def do_sort(ar, i, j):
    """Sorts the array ar from index i to index j."""
    if i >= j:
        return
    else:
        m = (i + j) // 2
        do_sort(ar, i, m)
        do_sort(ar, m + 1, j)
        if ar[m] > ar[j]:
            tmp = ar[j]
            ar[j] = ar[m]
            ar[m] = tmp
        do_sort(ar, i, j - 1)

```
> 0 votes

# Answer
This will almost work except when :-)

Language Python

```
>>> def sort(arr):
    _max = max(arr)
    buckets = [0]*(_max+1)
    for elem in arr:
        buckets[elem] = 1
    return (index for index, elem in enumerate(buckets) if elem == 1)

>>> list(sort(range(10,1,-1)))
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(sort([10**10, 1]))

Traceback (most recent call last):
  File "<pyshell#2012>", line 1, in <module>
    list(sort([10**10, 1]))
  File "<pyshell#2010>", line 3, in sort
    buckets = [0]*(_max+1)
OverflowError: cannot fit 'long' into an index-sized integer

```
> 0 votes

# Answer
# PYTHON

```
myArray = [0.2, 1.7534, 0.63, 12.435, 23.0, 7.6, 8.2, 0.7, 3.9]
myArray.sort()
print(myArray)

```
> 0 votes

# Answer
I actually saw someone implement this in my undergrad. Start at the min value in the array, and iterate to the max value with some epsilon threshold. An order of magnitude increase in efficiency is an order of magnitude increase in runtime!

Luckily, the code is linear in the size of the array.

https://github.com/artoonie/shittycode/blob/master/sort.cpp
> -1 votes

---
Tags: code-challenge, popularity-contest, code-trolling
---