I need a program where the user inputs an array of doubles and the program outputs the array sorted

280

134

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.

Victor Stafusa

Posted 2013-12-27T09:17:45.597

Reputation: 8 612

Are you also allowed to use other languages than C? – ProgramFOX – 2013-12-27T09:25:29.977

Perhaps. I really want to avoid a case where just the choosen language is enough reason to troll the lazy OP. Otherwise, you could just plainly encode the correct solution using brainfuck, golfscript or some crazy language, but this would ruin the intention of this as everybody would do that. But if you use, lets say Java, C++ or Ruby, it would be ok. Further, in most homework questions the OP says what language he wants. – Victor Stafusa – 2013-12-27T09:33:10.180

OK, thanks. I just wanted to know whether I could use C#. – ProgramFOX – 2013-12-27T09:34:30.593

1“Crazy language”? I think the expression you are looking for is esoteric language. – manatwork – 2013-12-27T09:39:37.133

@ProgramFOX I edited the question to clarify your point. – Victor Stafusa – 2013-12-27T09:40:23.157

1@manatwork Not exactly. Although this englobes all (or almost all) esoteric languages, there might still be non-esoteric languages that are too crazy for that, e.g. no one would think in using Logo for this, except if trolling. Anyway, I let that be a bit subjective. The chosen language should not be the sole reason of the trolling, and people are discouraging to upvote answers that uncreatively abuses the language choice. If you are intending in abusing the choosen language, be really creative about that. – Victor Stafusa – 2013-12-27T09:53:35.180

48Stack Oversort – ThiefMaster – 2013-12-27T13:26:31.133

hmm... using code from [this question](Cardinal Numbers in Standard American English) and sorting the result? – SeanC – 2013-12-27T14:26:04.310

1This is going to be a great tag. Had to laugh at quite a few posts here, but I think it isn't going to attract a whole lot of OP's. Anyway, nice :) – tomsmeding – 2013-12-27T14:52:53.503

1

This reminds me of something we did for someone suspected of using us for a homework problem: Could U do it better?.

– IQAndreas – 2013-12-27T15:00:24.087

Isn't better to just post the link to good resource, where he/she could learn something ? Instead wasting his/her time and trolling ? – Paul Brewczynski – 2013-12-27T15:47:51.737

6@bluesm If someone has already decided to ask someone else to solve their problem instead of "wasting" their own time learning, posting a link to where they can learn on their own isn't going to do any good. – IQAndreas – 2013-12-27T16:21:21.380

"The idea of this category is..." - it seems like this belong on the tag wiki, not in the question itself. – Dukeling – 2013-12-27T17:12:06.417

2@Dukeling Yes, this is true. But since this is the first question in the category, I added the description here to introduce it. Further questions could simply reference the category and go to what the lazy OP asks. – Victor Stafusa – 2013-12-27T17:14:09.013

That does make sense, but the problem is that, if someone who already knows about this (presumably from other, newer questions) comes across this question, about 90% of the question would be unnecessary. Given that [se] questions are supposed to be in it for the long run, I don't think it should be here. Rather in the tag wiki with an associated Meta post, if any discussion is desired. But anyway, that's just my opinion. – Dukeling – 2013-12-27T17:30:21.140

I believe the category would be better if the rules stated that the program should seem ok to the lazy student, but absolutely not to their professor. Otherwise we will get print [the output requirement from spec] in every question at least once. – shiona – 2013-12-27T18:15:29.483

I suggested an edit to the tag wiki of code-trolling. Not sure if we should edit the description out; I'll leave that up to the OP/other users – Doorknob – 2013-12-27T18:18:06.590

1

I opened a meta discussion for the rules, hoping if will be of help: http://meta.codegolf.stackexchange.com/questions/746/code-troll-rules

– shiona – 2013-12-27T19:47:57.123

2silly, what is the point? to humiliate and discourage? i get that sometimes people are just trying to get their homework done, but really its easier just to say so and point them in the right direction. – Matt Evans – 2013-12-27T21:31:44.760

1At this rate, you might get the second ever Great Question badge on this site :-D – Doorknob – 2013-12-27T22:15:34.040

Given the limited state of a lot of PRNGs, I wonder how many of these bogosorts are actually capable of terminating at all on non-trivial input. – sh1 – 2013-12-28T00:57:33.030

3Wow, this question's about to get 100 upvotes and 10,000 views in less than 24 hours! – Joe Z. – 2013-12-28T01:37:24.733

2@JoeZ. Yeah, I could not even dream about that before. Totally awesome. I am very pround of this and would like to thank everybody. – Victor Stafusa – 2013-12-28T01:41:12.680

2

So, @Victor, I decided to continue the trend, to help expand the category.

– Joe Z. – 2013-12-28T01:53:33.843

1@JoeZ. You were right. It got 100 upvotes and 10,000 views in less than 24 hours (it took some 18 or 19 hours)! Further it already has 80 answers. Got two gold badges! – Victor Stafusa – 2013-12-28T02:40:59.737

18My goodness, Victor, your About box is so sad... we all have our ups and downs but you shouldn't beat yourself up man. You're a hero for Code Golfers everywhere now! – SimonT – 2013-12-28T04:21:35.767

2This is definitely the first question I have ever seen that has more than 100 answers.... Is this good or bad? – Justin – 2013-12-28T09:48:23.580

4

I'm surprised no one has offered a solution based on sleep sort yet

– Frank Farmer – 2013-12-28T11:02:54.410

2It's not "give-me-dah-codez", it's "plzsendtehcodz"! – The Guy with The Hat – 2013-12-28T13:04:59.637

1There should be some (manually awarded) badge for giving this type of answer - like Sheldon Cooper badge. – Konrad Morawski – 2013-12-28T15:55:35.620

Wow, there are 6 questions from this site on the hot questions list, and 5 of them are [tag:code-trolling] – Justin – 2013-12-28T18:17:24.503

@Quin Ahahaha, not sure if that's great or... XD – Doorknob – 2013-12-28T18:51:20.580

1

This is like Photoshop Trolling. Warning: hilarious.

– Chloe – 2013-12-28T19:21:55.303

Explanation of a new class of questions should have gone on meta first and then migrated to the tag wiki once something was settled. – dmckee --- ex-moderator kitten – 2013-12-28T20:45:22.050

I found that it's very strange that on one mentioned Shell Scripting before, so I posted my answer which, in a nutshell, is a call to the sort -n command. – Damkerng T. – 2013-12-28T22:31:13.887

Not worth the effort to code it so I'm not entering, but my suggestion for an easy-to-understand pessimized sort routine would be to random shuffle and then check whether they're ordered yet. – keshlam – 2013-12-29T21:47:20.690

@keshlam, that's bogosort, and there are several of them posted already. However, I assert that my entry is less efficient than bogosort for array lengths less than about 20. – sh1 – 2013-12-30T01:35:17.577

Too short for an answer, here is T-SQL version (minus CR-LF): create type dbo.ArrayOfDouble as table ( Item float(53) ) go

create function SortArrayOfDouble ( @array ArrayOfDouble readonly ) returns table as return ( select Item from @array order by Item ) go – Pieter Geerkens – 2014-01-01T00:14:29.280

1Wow, this now has 2^8 upvotes! – Cruncher – 2014-01-16T18:21:33.197

Code-trolling is in the process of being removed, as per the official stance. This question has historical value for obvious reasons, so it is being kept around, but I am locking it now.

– Doorknob – 2014-05-10T16:08:26.877

Answers

178

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++);
  }

AShelly

Posted 2013-12-27T09:17:45.597

Reputation: 4 281

32almost all the advice is wrong, and it simply keeps asking for the input list until you enter it already sorted. – AShelly – 2013-12-27T16:44:11.027

47+1, for 1st, 2th, 3th, 4th... and the downto operator--very advanced C programing techniques. – Kaya – 2013-12-27T17:31:58.197

5Should use sscanf(input, "%5s", &input[0]), otherwise there might be overrun bugs while parsing the input. And input should be declared char input[sizeof(int)+1], for backward compatibility with 64-bit systems. – sh1 – 2013-12-28T01:17:23.730

12i==1?"st":"th" hahaha... – Guy Sirton – 2013-12-28T07:42:37.227

1Java is not a scripting language... – Justin – 2013-12-28T07:58:40.953

15Java has garbage collection. Therefore Java is for "scripting", not real programming. That's basic CS101. (so says the troll.) – AShelly – 2013-12-28T08:20:50.503

2@AShelly this is perfect, has all the nuanced hallmarks of the self-taught know-it-all C lifer. – joerick – 2013-12-28T19:10:03.110

2Good thing you remembered to put the calloc parameters in the right order! It creates such hard-to-find bugs when they are mixed up. – Emil Vikström – 2013-12-29T06:52:46.277

1You forgot to free the calloc'ed memory. That's something one should never forget! To be on the safe side, free before the until-loop – Hagen von Eitzen – 2013-12-29T13:42:38.700

What is this line doing? Tokenizing the first value from the line? sscanf( input, "%s", &input[0] ) – redolent – 2013-12-29T22:05:19.930

I love this entire thing, but +1 for the i==1?"st":"th" and "scripting in Java" troll comment ;) – Wayne Werner – 2013-12-29T22:14:15.767

@redolent, sscanf stands for "String SCAN Format", so it's obviously taking the input String and Scanning it into the correct Format. As you probably know, passing an unformatted string to atol would cause undefined behavior. – AShelly – 2013-12-30T04:32:14.490

1I really do not want to accept my own answer. So, I will wait a bit more to see if this answer eventually beats it. – Victor Stafusa – 2013-12-30T04:46:15.003

1Now I am going to want until every time I have to use while (!condition) – dansalmo – 2013-12-30T16:50:26.250

4

@GuySirton That i==1?"st":"th" isn’t so hot. At ELU we prefer i >= 10 && i <= 20 ? "th" : i%10 == 1 ? "st" : i%10 == 2 ? "nd" : i%10 == 3 ? "rd" : "th" instead, for cromulently self-evident reasons. :)

– tchrist – 2014-01-01T04:22:00.253

@tchrist, That's beauty of the simple version. If the OP tries to fix it, he gets lead down the path to madness leading to your version. – AShelly – 2014-01-05T22:39:46.110

1@AShelly One man’s madness is the previous one’s job security. The more I look at your answer, the more I like it. – tchrist – 2014-01-06T00:34:34.560

1Telling a new programmer to use atol() - that's just mean :P – Tim Post – 2014-01-06T13:58:00.820

181

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);
    }
}

Victor Stafusa

Posted 2013-12-27T09:17:45.597

Reputation: 8 612

103That's actually a little too close to home for what many Java coders would consider an acceptable match of solution to spec!! – HostileFork says dont trust SE – 2013-12-27T12:00:26.130

10Also consider the case where you need to sort a very large number of objects. Sorting them "outside the program" in a database is a feasable solution. – Viktor Seifert – 2013-12-27T12:44:57.930

40Not enough abstraction here. You need at least 10 interfaces, 20 implementations, enums, unit tests, coverage tests, Maven, integration tests, mocks... – Naftuli Kay – 2013-12-27T19:47:02.643

2

@NaftuliTzviKay- Good point, but there needs to be some factories as well. http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12

– Adrian Carr – 2013-12-27T20:53:55.403

6@NaftuliTzviKay We should create a MySQLSortEnterpriseEdition to implement your idea. Will Victor agree to GPL-license the code here so we can get started? – Joe Z. – 2013-12-27T21:32:31.450

14@JoeZ. Yes, my answer is lacking comments about the licensing model and I should make the user accept an EULA in the start of the program. But since I am giving it to the lazy OP, it is free for non-commercial use, including being useful to create the long-awaited premium MySQLSortEnterpriseEdidtion. – Victor Stafusa – 2013-12-27T21:39:10.967

(Technically it's CC-BY-SA already which is copyleft like the GPL and allows for commercial use, but I just wanted to get it under GPL because CC-BY-SA isn't supposed to be used for software.) – Joe Z. – 2013-12-27T21:44:36.177

1In college, our fraternity gave gag gifts and the worst thing was if it was in any way useful. Despite @victor's best efforts, this is USEFUL, USEFUL, BOOOO! – bmike – 2013-12-27T22:55:19.750

I'm with @ViktorSeifert on this one. When you have too much data to store in memory all at once, using a preexisting external system that can already use the filesystem to sort the data in parts - like a database - is a natural solution. – Izkata – 2013-12-28T04:08:31.280

4@Izkata Except if this is a homework about developing sorting algorithms, which should have nothing to do with databases. – Victor Stafusa – 2013-12-28T04:11:06.963

2Surely this will actually be faster than a fully-Java implementation? – None – 2013-12-29T06:07:59.213

Why not to give SQL query as solution itself? – Szymon Toda – 2013-12-29T13:39:51.340

1Replace MySQL with SQL Server. Maybe there is some check you can do to make sure it's Enterprise edition which would take thousands of dollars to install. – Charity Leschinski – 2013-12-29T16:11:05.107

2Unfortunately, as this requires a running MySQL server, the OP may just reply with "the codes doesn't work." Better would be to use SQLite or some other Java database library like H2 where you have no external system dependencies. – Christopher Orr – 2013-12-30T10:48:03.003

1We can read the data from XML with some complex xml library before inserting into database. – Emmanuel John – 2014-01-01T10:25:47.737

1I'd prefer MariaDB. – MDMoore313 – 2014-01-01T17:22:40.293

2This isn't international, I don't see a LANGUAGES table. – Adam Davis – 2014-01-13T20:15:48.153

142

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);

SWeko

Posted 2013-12-27T09:17:45.597

Reputation: 1 101

49Lol, ListSort Enterprise Edition© :-P +1 – Doorknob – 2013-12-27T22:21:05.423

14+1 for crazy overcoding. I suggest you break your answer into 3 or more 'module' answers so that I may +1 them individually – greggo – 2013-12-27T23:50:58.267

15And the cherry on top is that it's actually using a library sort:) It's completely to the spec, and completely useless – SWeko – 2013-12-28T00:28:31.463

Oh My God. Overkill indeed. – Newb – 2013-12-28T02:35:48.663

6Can we please reuse this freely for all questions? – SimonT – 2013-12-28T04:11:33.987

1@SimonT, We might, It sure is extensible enough. – SWeko – 2013-12-28T06:31:43.560

9That... was... beautiful. – Andrew – 2013-12-28T06:55:27.373

1You spent a lot of time for this trolling. Bravo! I'm impressed... +1 – Kiruse – 2013-12-28T11:43:46.437

3You should package this on NuGet to see how many people actually check what they're using. :) – Liam Dawson – 2013-12-28T13:18:06.130

3Introducing a proper DI framework would help you getting rid of all those factories. – Sebastian Graf – 2013-12-28T15:46:03.420

7Using DI will just confuse the OP, as this is just a quick example. – SWeko – 2013-12-28T16:29:29.907

3I love that it'll try to instanciate every type in the executing assembly, three times! Perhaps even some unsafe native handles that are just created for no reason for the GC to collect :). – Aidiakapi – 2013-12-28T19:34:43.227

SimonT, it's Creative Commons so just give proper attribution ;-) – Emil Vikström – 2013-12-29T07:17:45.030

3Is it bad that this is what I consider to be the typical non-joke Java enterprise code to look like? – DVK – 2013-12-31T00:56:40.560

1http://harmful.cat-v.org/software/_java/problem-factory.jpg. Works for C# as well. – SWeko – 2013-12-31T07:49:01.217

This is very good, but one thing that would have made it even better would be to use generic types. After all, how do we know that it's really going to be an array of doubles and not, say, integers or even strings? I'd love to see a version with IArrayReader<T>, IArrayProcessor<T>, and IArrayWriter<T>, along with the mind-bending reflection code to accompany it. – Aaronaught – 2014-01-05T23:43:18.057

@Aaronaught, nah, that might be actually useful. A IDoubleArrayFactoryManager<T> might be a more generic approach, how that I think of it. – SWeko – 2014-01-06T12:31:37.163

1That's sooooo evil. And, because of that, beautiful – Fabricio Araujo – 2014-01-07T20:35:22.523

132

Even more literal interpretation:

echo " aaehrrty"

that is, "the array" sorted.

RBerteig

Posted 2013-12-27T09:17:45.597

Reputation: 1 139

5I came here to post this. – Quuxplusone – 2013-12-28T17:08:39.567

5save as file sort.sh and call as sh sort.sh "an array of doubles" – Kyss Tao – 2013-12-28T21:29:08.333

I think you missed the "the user inputs an array of doubles". – Dukeling – 2014-01-01T23:25:53.810

1@Dukeling that's the point of what Kyss Tao's comment. "an array of doubles" can be passed to the script as a command-line argument. – AJMansfield – 2014-01-02T21:21:52.303

108

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.

PhiNotPi

Posted 2013-12-27T09:17:45.597

Reputation: 26 739

3evil! evil! evil! – DGM – 2013-12-28T00:24:39.383

56about as decipherable as any other Perl script to me :) – Corey Goldberg – 2013-12-28T00:32:35.307

Brilliant! This is probably the most intimidating to a newcomer. – Newb – 2013-12-28T02:33:55.373

I think you probably need a comment for this one tricky part:

"print;"

OP might not know that Perl will print the contents of $_ if nothing is specified. – swelljoe – 2013-12-28T02:54:52.697

6@swelljoe Actually, $_ is an empty string at that point. I stored my desired output in $\, which is the output record separator. – PhiNotPi – 2013-12-28T02:58:03.153

Brilliant. Never would have considered using $\\ as a side effect. +1 – khoxsey – 2013-12-28T05:19:38.860

I would love to see the professor's comments upon the student turning this in as his/her homework. – Andy – 2013-12-28T08:05:15.707

4@Andy simple. "How does it work?" – John Dvorak – 2013-12-28T18:35:28.543

1and all user-created variables have pretty names that follow all thinkable conventions – Hagen von Eitzen – 2013-12-29T13:49:23.130

80

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.

Winston Ewert

Posted 2013-12-27T09:17:45.597

Reputation: 1 051

1Please see other answers before posting your own. You should add the name of your language. To answer this question you also need to briefly explain what you are doing to troll the OP. – Wasi – 2013-12-27T17:14:55.923

5Hehe, this one actually made me laugh out loud. Anyway, I agree that a little better explanation would be helpful. – oconnor0 – 2013-12-28T03:49:21.373

2Is the double call to sys.stdin.read() a typo or part of the real trolling-answer? Surely it would frustrate the OP to give the array as input and continue to wait for the result... – Bakuriu – 2013-12-28T07:51:56.980

Wow, that's evil all right. – Sylverdrag – 2013-12-28T14:02:57.260

@Bakuriu, that was a typo, although it would make good troll as well. But I figure one troll per answer, so I fixed it. – Winston Ewert – 2013-12-28T17:08:36.587

Why not just import someoneElsesDoubleArraySorter, and just have it work magically? – Alexander - Reinstate Monica – 2013-12-30T05:06:36.473

13A O(n) sort algorithm. Nice. – ejrb – 2014-01-02T13:59:12.950

65

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

Riot

Posted 2013-12-27T09:17:45.597

Reputation: 4 639

11Trolling 1: The algorithm does work, but is obviously potentially extremely slow - it spawns a thread for each number, sleeping for that number of seconds before outputting the number (which is thus in order). Trolling 2: Additionally, most of the code is spent on writing a nice comment about how many threads its spawning, and unnecessarily and gratuitously reads and parses the system's cpu info just for the sake of some extra verbose output. Trolling 3: It outputs "the array sorted" at the end, which seems to be the done thing. Trolling 4: The user cannot cancel the "sort" by hitting ctrl-c. – Riot – 2013-12-28T01:03:28.877

4 start="5">

  • It only works on GNU/Linux, due to use of /proc/cpuinfo.
  • < – kps11346 – 2013-12-28T02:37:59.390

    5Extremely creative solution, by the way :) – dmitry – 2013-12-28T19:37:50.883

    8This is amazing. I can't even express how awesome that is. I'm considering using that actively, because WHY NOT. – None – 2013-12-28T20:37:26.210

    4I actually genuinely do have a variant of this in use in production somewhere. But in that situation, the runtime of the process is important, so that's my excuse... – Riot – 2013-12-28T21:01:26.533

    -1 for using bash instead of /bin/sh :) – DVK – 2013-12-31T01:04:47.847

    2 start="6">

  • It counts hyperthreading cores, not physical cores.
  • < – Emil Vikström – 2014-01-01T13:13:11.927

    3And of course: 7. Concurrency issues! Numbers below or close to 0.0 may be printed before the friendly prompt. 8. Negative numbers gives errors. – Emil Vikström – 2014-01-01T13:15:31.497

    1@kps11346, /proc/cpuinfo is in cygwin of all things, so this is cross-platform portable code! – Brian Minton – 2014-01-02T15:56:59.983

    1This solution made me LOL. Great job! – Brian Rogers – 2014-01-04T22:06:11.343

    2I don't have a GNU/Linux OS to test this on, but I'm pretty sure there's a (9) - similar numbers won't get sorted correctly if the array is large, e.g. if you have 1.01 at the beginning and 1.00 at the 1000th position. So that's +1 for a solution which will probably appear to work for all the trivial test cases the naïve copy-paster will try, but probably end up with subtly incorrect behaviour in "production" (e.g. when the teacher/professor tests it with a much larger input). – Aaronaught – 2014-01-06T00:05:07.740

    64

    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.

    Alexey Lebedev

    Posted 2013-12-27T09:17:45.597

    Reputation: 741

    8That's even better because it's a built-in function. – Wayne Werner – 2013-12-29T22:52:54.337

    62

    (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();
    

    Felipe Miosso

    Posted 2013-12-27T09:17:45.597

    Reputation: 711

    72"-1 not enough jQuery" – grc – 2013-12-27T14:18:48.523

    55I particularly like how this doesn’t actually use jQuery. – KRyan – 2013-12-27T15:24:52.807

    8-1 Your array naming must include Hungarian notation in it, specifically jQuery objects signified using $, arrays using a and results of window.prompt as p. – Qantas 94 Heavy – 2013-12-27T15:48:40.713

    Too bad that I can't upvote twice. It is brilliant how you could be so evil in so many different aspects. – Victor Stafusa – 2013-12-27T23:43:19.453

    Write this code was really fun! – Felipe Miosso – 2013-12-28T00:22:04.793

    2The "tricky part" is elegant. OP, strive to have that kind of code structure someday. – Chris Barker – 2013-12-28T08:05:57.660

    2That F'n doble "validation" LOOOOOOOOOOOOL omg omg day made! edited for less caps – HC_ – 2013-12-30T18:00:24.313

    I like the idea of an answer that can only ever sort exactly 3 numbers. Which is why I don't like the last few lines; even though it's pretty funny that you totally throw away everything done so far and just use a library function, it also makes it not a very good troll because the OP could pick up on that and use it to write a program that actually works. I think the whole idea is to end up with code that's not just inefficient and subtly broken but also nearly impossible to adapt, improve or fix. Same idea with the for-if loop; too TDWTF-y, it's pointless but also easy to remove. – Aaronaught – 2014-01-05T23:53:56.547

    For a guy (OP) who doesn't even know how to sort an array, I would be surprised if he could easily do anything =) – Felipe Miosso – 2014-01-06T00:31:15.497

    54

    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!

    Doorknob

    Posted 2013-12-27T09:17:45.597

    Reputation: 68 138

    4Expanding on the idea, I would repeatedly ask for input until the user inputs the string an array of doubles. – Wrzlprmft – 2013-12-27T17:56:37.100

    @Wrz Ok, done :-) – Doorknob – 2013-12-27T17:59:16.040

    2That's extra great because the poor OP will have to figure out how to get rid of a newline (because you use gets instead of gets.chomp). – wchargin – 2013-12-27T21:17:39.370

    @WChargin Yep, I had that in the first revision (see revision history) but removed it to be even more evil >:D EDIT: Oh wait, never mind, that was my other answer. I'll edit this one :-) – Doorknob – 2013-12-27T21:45:30.687

    1+1 I created an account here just to say, this is exactly how I would answer it! Love it! – DGM – 2013-12-28T00:10:08.357

    I love the g = gets until ... idiom. – John Dvorak – 2013-12-28T18:37:48.740

    You could do g = gets until /^an array of doubles\n$/ to be even more evil – John Dvorak – 2013-12-28T18:38:54.730

    @Jan Heh, that actually works? Confuse the OP even more! :-D editing – Doorknob – 2013-12-28T18:48:59.663

    This is now my top voted answer. Not sure if I should be proud, or sad...? – Doorknob – 2013-12-29T14:41:54.853

    54

    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");
    }
    

    Mark Plotnick

    Posted 2013-12-27T09:17:45.597

    Reputation: 1 231

    4Or a "script": #!/usr/bin/sort. – Mechanical snail – 2014-01-18T04:32:33.733

    44

    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.

    Bakuriu

    Posted 2013-12-27T09:17:45.597

    Reputation: 781

    3I think this could use more explanation; what are you doing to the Inferno now? – KRyan – 2013-12-27T14:35:22.200

    1Wow, you can do non-ascii variable names in python? didn't know... – kratenko – 2013-12-27T15:27:09.923

    1@kratenko From python3+. In python2 the interpreter assumes ASCII as encoding and would have raised an error. In python3 the interpreter assumes UTF-8 as encoding and accepts all characters that are "letters" by unicode properties for identifiers. – Bakuriu – 2013-12-27T15:48:25.350

    3@KRyan: He's obviously employing the sorting method that Hell uses to get people into the nine circles. – Joe Z. – 2013-12-27T16:18:23.500

    1you're an evil man – Corey Goldberg – 2013-12-28T00:31:00.427

    10Oh my goodness… +1 for è. – Sean Allred – 2013-12-28T02:59:19.203

    Shows the OP that you should have multiple keyboard layouts to access an adequate variety of possible variable names (e.g. è). – SimonT – 2013-12-28T04:10:27.060

    Well, there can be good reason for it, @SimonT. http://programmers.stackexchange.com/q/16010/2406.

    – TRiG – 2013-12-28T07:00:09.563

    41

    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

    shiona

    Posted 2013-12-27T09:17:45.597

    Reputation: 2 889

    This has undefined behavior for all inputs greater than 7 bytes. Not an acceptable answer. – Michael Spencer – 2013-12-28T03:53:41.477

    1Love the "Pessimal Algorithms" paper; thanks. – Ryan – 2013-12-28T06:48:49.643

    “The slowest deterministic sorting algorithm I'm aware of” – the provably slowest deterministic sorting algorithm. That’s the whole point of the paper, AFAIR. – Konrad Rudolph – 2013-12-28T09:20:37.167

    @MichaelSpencer Care to elaborate? I gave an example with input size 24 bytes and the output is what one would expect (I think I might be missing a joke here). – shiona – 2013-12-28T09:38:04.027

    @Konrad I can't find a proof of the pessimality of the algorithm in the paper. – shiona – 2013-12-28T09:39:29.923

    You can surely do worse, with any recursive algorithm that effectively tries all possible permutations of the input. – Sasho Nikolov – 2013-12-28T10:33:18.037

    2@Sasho but a bogo-sort has best-case running time of \Omega(n) (n-1 comparisons, 0 operations). That's much faster, aka. worse, than \Omega(n^(log n/2)). – shiona – 2013-12-28T10:40:36.677

    @shiona Best case complexity is almost never used as a metric. But I also don't think there's such a thing as a worst algorithm. For instance I could write an algorithm that given a list of size $n$ first performs $A(n,n)$ comparisons where $A$ is the Ackermann function and then runs mergesort on the list. This is astronomically worse than the sort you've provided and is still deterministic. It could of course be made worse by performing even more comparisons, such as $A(A(n,n),A(n,n))$.

    – JSchlather – 2013-12-29T10:08:28.003

    @JSchlather True. Maybe the wording should be "Deterministic algorithm that has the largest best case running time s.t. the number of inversion never increases and no comparisons are made between elements whose order is trivially (without keeping an extra datastructure) known." I'm probably still missing something here. But really, my point wasn't to prove anything, I just wanted to give some people a good laugh. – shiona – 2013-12-29T14:05:14.820

    39

    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 * ","
    

    Doorknob

    Posted 2013-12-27T09:17:45.597

    Reputation: 68 138

    Why not bogobogosort? (runs in a quaint O(n * (n!)^n) time)

    – wchargin – 2013-12-27T21:20:25.177

    @Wchargin I may consider it :-) you may be interested in my recent edit! (Sorry for being slow, I'm actually on my phone right now since I can't access a computer :-P) – Doorknob – 2013-12-27T21:57:38.623

    37

    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.
    

    rolfl

    Posted 2013-12-27T09:17:45.597

    Reputation: 521

    6Only you would use COBOL for an answer to this question. +1 – syb0rg – 2013-12-27T22:02:16.000

    5Ah, the fresh smell of punch cards – Sklivvz – 2013-12-28T09:49:26.500

    3@EbenezerSklivvze - LOL. I once took out a punched card I was using as a bookmark when my Assembly college professor was telling the class about oldtimey punched cards. He was sufficiently floored (it was in 1994 :). Don't think many of my contemporaries ever saw a whole deck... – DVK – 2013-12-31T01:02:05.877

    30

    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]

    Kiruse

    Posted 2013-12-27T09:17:45.597

    Reputation: 311

    4"Assuming datatype double but interpreting it as duplicates". Only a truly genius would think that way. Just brilliant! – Felipe Miosso – 2013-12-27T15:59:02.203

    @FelipeMiosso To be honest, I'm not sure if you're just being sarcastic... – Kiruse – 2013-12-27T17:26:13.690

    1Haha ... I was being sarcastic. I know there are people out there who really think that way. Anyway ... your answer was epic! I laughed a lot. – Felipe Miosso – 2013-12-27T17:39:30.540

    @FelipeMiosso Glad I could help make a laugh. ;) – Kiruse – 2013-12-27T20:12:23.570

    console.log everything! – Emil Vikström – 2013-12-29T07:24:31.963

    Not enough jQuery. – Pierre Arlaud – 2014-01-02T13:44:58.370

    28

    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));
    ?>
    

    totymedli

    Posted 2013-12-27T09:17:45.597

    Reputation: 361

    25

    [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]

    kps11346

    Posted 2013-12-27T09:17:45.597

    Reputation: 181

    3But the problem was to sort the doubles. Nobody required the values to be in (total)order. For example you could sort the array into two, positive and negative numbers. You were doubletricked by the question. – shiona – 2013-12-27T18:10:06.917

    25

    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).

    user974006

    Posted 2013-12-27T09:17:45.597

    Reputation: 349

    +1 I thought about using next_permutation for my answer, but this is a lot cleaner than what I had in mind. – jliv902 – 2014-01-06T14:39:41.517

    23

    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!

    Briguy37

    Posted 2013-12-27T09:17:45.597

    Reputation: 2 616

    Nice idea. You must have been cool when you were still a programming newbie. – Pierre Arlaud – 2014-01-02T13:47:46.977

    22

    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.

    syb0rg

    Posted 2013-12-27T09:17:45.597

    Reputation: 1 080

    10This is useful and thus worthy of a down-vote. – emory – 2013-12-27T20:13:24.833

    @emory It points the OP to the correct useful answer, but really isn't useful within itself (to a new programmer). I don't think it warrants an un-upvote. – syb0rg – 2013-12-27T22:10:42.270

    11"Indirectly telling the OP to do his own research while giving him a vague correct answer" pretty much describes my style of StackOverflow answering :/ – Corey Goldberg – 2013-12-28T00:37:25.280

    @CoreyGoldberg Do you also point to older documentation? ;) – syb0rg – 2013-12-28T00:39:08.027

    @syb0rg definitely not. (though all document links are somewhat ephemeral anyway) – Corey Goldberg – 2013-12-28T00:42:44.063

    7"Take a look at Arrays.sort()" ... "Could I get an example how to use it in my program?" ... brilliant. – SimonT – 2013-12-28T04:14:25.157

    5+1 especially because our humble OP probably needs to write a sort him/herself for a class, making Array.sort() completely useless to him/her. – Kevin – 2013-12-28T07:25:10.097

    1@CoreyGoldberg I like your style of SO answering; I wish more people would do this. – None – 2013-12-28T18:22:09.650

    2Ctrl + F -> "Could I get an example how to use it in my program?" = 3 results. – Qix - MONICA WAS MISTREATED – 2013-12-30T03:17:18.380

    @Corey Goldberg, that's how you should answer most questions. – d-_-b – 2014-01-01T03:23:19.503

    21

    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...

    luksch

    Posted 2013-12-27T09:17:45.597

    Reputation: 321

    Is calling this GA or Monte Carlo another level of troll? I believe this is a randomized hill-climbing algorithm. – shiona – 2013-12-27T20:17:53.287

    associating this program with buzzword names was intentional, but I never heard of "randomized hill-climbing algorithm" either... and in a broader sense I think GA and Monte Carlo are not too far off to be plainly wrong... – luksch – 2013-12-27T20:25:58.933

    19

    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.

    grc

    Posted 2013-12-27T09:17:45.597

    Reputation: 18 565

    5Unfortunately, this is trivially fixed by removing everything after lambda x: and replacing it with x. Still, a beginner coder would never know that, so kudos! – Joe Z. – 2013-12-27T15:54:22.033

    18

    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 ;
    }
    

    jliv902

    Posted 2013-12-27T09:17:45.597

    Reputation: 221

    6Your sort “algorithm” had me in tears. – Nate – 2013-12-27T22:42:20.253

    Hah, that is not an algorithm because it is not granted to finish >:D – jmacedo – 2013-12-31T05:50:48.733

    @joxnas, actually on systems where non-deterministic random devices are not available, the randomizer may actually be periodic. Then it would simply depend on whether the set of possible permutations allowed by the randomizer subsumes the set of possible permutations $S_n$ for all possible input array lengths $n$. – bug – 2013-12-31T19:16:48.683

    Aw pants, I forgot LaTeX was only supported on TeX.SE and Math.SE. Just imagine those symbols in snooty italix. – bug – 2013-12-31T19:18:23.953

    18

    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.

    Sylverdrag

    Posted 2013-12-27T09:17:45.597

    Reputation: 181

    2You say 'feast your eyes' and give me PHP O.o – Aidiakapi – 2013-12-28T19:53:12.727

    3"Evil" was part of the requirements, wasn't it? – Sylverdrag – 2013-12-29T10:26:34.783

    17

    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!
    }
    

    scrblnrd3

    Posted 2013-12-27T09:17:45.597

    Reputation: 1 554

    6

    Credit where credit is due: http://www.dangermouse.net/esoteric/intelligentdesignsort.html

    – wchargin – 2013-12-27T21:21:22.537

    1Don't understand why you bash intelligent design in a programming contest? – khebbie – 2013-12-28T08:00:03.077

    12@khebbie Why not? – Konrad Rudolph – 2013-12-28T09:19:10.613

    Problem is, if the user is the one who input the numbers, then they would be more intelligent than themselves. ;) – d-_-b – 2014-01-01T03:27:50.730

    16

    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.

    Joe Z.

    Posted 2013-12-27T09:17:45.597

    Reputation: 30 589

    4It's also particularly devious in that if all the numbers have the same number of digits before the decimal point, it will actually work correctly, so the OP might not even notice that the sort is doing something wrong if he just tests it using an input of, say, 2, 1, 3, 8, 5. – Joe Z. – 2013-12-27T15:59:10.997

    14

    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

    planetguy32

    Posted 2013-12-27T09:17:45.597

    Reputation: 411

    11

    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.

    HostileFork says dont trust SE

    Posted 2013-12-27T09:17:45.597

    Reputation: 2 292

    6Maybe they need to be halved since the input is already doubled! – kealist – 2013-12-27T15:13:23.133

    @kealist I considered that, however this plays on the idea that "doubling" is taking place. I think it sneaks by a little better to have the [2 * num]. – HostileFork says dont trust SE – 2013-12-27T15:20:19.313

    10

    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.

    Valentin CLEMENT

    Posted 2013-12-27T09:17:45.597

    Reputation: 321

    10

    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.

    Dryden Long

    Posted 2013-12-27T09:17:45.597

    Reputation: 217

    1+1 for "This code is only a few short lines, so you know it must be efficient!" – greggo – 2013-12-27T23:49:12.853

    @greggo I'll be honest, I would have fallen for that at one point in time haha – Dryden Long – 2013-12-28T00:31:49.420

    I must say the brilliance of changing [ 5, 1, 4, 0, 3 ] into [ 1.5, 2.1, 3.4, 4.0, 5.3 ] was great :) – Aidiakapi – 2013-12-29T15:51:54.913

    8

    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);
        }
    }
    

    Victor Stafusa

    Posted 2013-12-27T09:17:45.597

    Reputation: 8 612

    7

    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]");
    }
    

    Victor Stafusa

    Posted 2013-12-27T09:17:45.597

    Reputation: 8 612

    6

    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;
    }
    

    emory

    Posted 2013-12-27T09:17:45.597

    Reputation: 989

    2+1 because this algorithm is just ridiculous. It has an evil twist: Since you are comparing the reference of the parameter with the reference of the local variable and not the actual contents of the array, this will always throw the exception. – Victor Stafusa – 2013-12-27T18:52:20.647

    @Victor I suppose if I had bothered to test it, I would have fixed that and the algorithm would work for some test input (which was my goal). But I am too lazy for that. – emory – 2013-12-27T19:08:58.537

    6

    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.

    Wrzlprmft

    Posted 2013-12-27T09:17:45.597

    Reputation: 2 772

    5

    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))))
    

    Sylwester

    Posted 2013-12-27T09:17:45.597

    Reputation: 3 678

    Can you even have (shuffle ar) change ar as side-effect in CL, or is that a deliberate endless recursion? – Christopher Creutzig – 2013-12-27T18:29:07.983

    @ChristopherCreutzig Arrays are mutable atoms so it is a possible legit BogoSort :-) – Sylwester – 2013-12-27T19:58:02.883

    5

    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.

    Brian S

    Posted 2013-12-27T09:17:45.597

    Reputation: 131

    5

    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())));
    

    tia

    Posted 2013-12-27T09:17:45.597

    Reputation: 745

    5

    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? ;)

    Konijn

    Posted 2013-12-27T09:17:45.597

    Reputation: 505

    I like it, but it could use improvement. Change the function signature to `function sortDoublesFast(aSmallDouble,aLargeDouble) and you can return a constant. – emory – 2013-12-27T19:40:44.330

    5

    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 :)

    aditsu quit because SE is EVIL

    Posted 2013-12-27T09:17:45.597

    Reputation: 22 326

    5

    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.

    MSalters

    Posted 2013-12-27T09:17:45.597

    Reputation: 171

    "The trick to a good fake answer is to make it look believable." I agree with this a lot. – Joe Z. – 2013-12-28T01:24:41.780

    5

    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);
    }
    

    japreiss

    Posted 2013-12-27T09:17:45.597

    Reputation: 121

    5

    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);
    }
    

    Casey Chu

    Posted 2013-12-27T09:17:45.597

    Reputation: 1 661

    5

    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

    hdante

    Posted 2013-12-27T09:17:45.597

    Reputation: 181

    1It would be cool to write a program that writes this program. – Alexey Lebedev – 2013-12-28T23:14:04.437

    5

    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
    

    Daniel S.

    Posted 2013-12-27T09:17:45.597

    Reputation: 131

    5

    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);
    }
    

    Alex Becker

    Posted 2013-12-27T09:17:45.597

    Reputation: 151

    This is incredible. – bright-star – 2013-12-29T00:23:50.633

    @TrevorAlexander It was much more of a pain to code than I expected. C really doesn't handle polymorphism well. – Alex Becker – 2013-12-31T00:37:52.513

    5

    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.

    jeremy

    Posted 2013-12-27T09:17:45.597

    Reputation: 151

    4

    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);
        }
    }
    

    dpatchery

    Posted 2013-12-27T09:17:45.597

    Reputation: 141

    Your target is treating them as Integer when they're doubles? Unfortunately, I think your target provides a too-easy-to-extract useful answer. – KRyan – 2013-12-27T14:39:03.623

    Oops, fixed to be Double. Fair point about the target though. – dpatchery – 2013-12-27T14:46:27.213

    Instead of directly comparing monkeys to the sorted list, you could make it even more obscure by iterating through it and checking to see that each double is less than the next one. Instead of exiting the for loop when you find that it's not in order, make sure to go all the way through and just keep an "isSorted" flag to make it extra inefficient ;) – Blackhawk – 2013-12-27T19:31:23.570

    4

    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
    

    Timtech

    Posted 2013-12-27T09:17:45.597

    Reputation: 12 038

    1Confused about :Lbl Banana with no :Goto Banana but I guess that's okay. – wchargin – 2013-12-27T21:25:41.430

    @WChargin Confusing ain't it? – Timtech – 2013-12-27T22:35:12.047

    2The Banana is just for scale... – Dryden Long – 2013-12-27T23:14:08.520

    4

    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";
    
    }
    

    Gary S.

    Posted 2013-12-27T09:17:45.597

    Reputation: 141

    Before you vote, please note: 1) fake algorithm name, 2) using Arrays.sort instead of addressing the obvious homework question of how sorting works, 3) unnecessary Comparator, which uses unnecessary recursion, 4) liberties taken (pun intended) with the output method, 5) observing worst practices in error handling (i.e. ignoring them completely), and 6) a special message for the TA. Thank you for your consideration. – Gary S. – 2013-12-27T17:22:44.607

    4

    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
    

    Lambda Fairy

    Posted 2013-12-27T09:17:45.597

    Reputation: 311

    4

    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 - Connecting
    Sorting - 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]

    C1D

    Posted 2013-12-27T09:17:45.597

    Reputation: 590

    3

    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.

    Wasi

    Posted 2013-12-27T09:17:45.597

    Reputation: 1 682

    What happens when the stupid user gives invalid input? – emory – 2013-12-27T20:16:17.937

    1@emory It doesn't work, of course. – Lambda Fairy – 2013-12-27T20:40:10.453

    @LambdaFairy does it fail silently, crash loudly, or is the behavior undefined? The most evil would be if the behavior was undefined and failed silently on the student computer and crashed loudly on the teacher computer. – emory – 2013-12-27T20:46:47.430

    3

    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(" "))
      }
    
    }
    

    Joe K

    Posted 2013-12-27T09:17:45.597

    Reputation: 1 065

    3

    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.]

    kps11346

    Posted 2013-12-27T09:17:45.597

    Reputation: 181

    3

    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.

    Luke Worth

    Posted 2013-12-27T09:17:45.597

    Reputation: 131

    1This is even funnier because quicksort in Haskell is like three lines. – wchargin – 2013-12-27T21:27:54.110

    3

    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.

    sh1

    Posted 2013-12-27T09:17:45.597

    Reputation: 121

    3

    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
    }
    

    syb0rg

    Posted 2013-12-27T09:17:45.597

    Reputation: 1 080

    3

    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.

    Joe Z.

    Posted 2013-12-27T09:17:45.597

    Reputation: 30 589

    If you want maximum fun, do bogosort with this instead. – Joe Z. – 2013-12-28T00:01:44.380

    Amazing. Best bogosort evar!!!! – Victor Stafusa – 2013-12-28T00:02:23.650

    Even worse, do bogosort by comparing two elements where the first isn't necessarily before the second. Then you'll never know whether you've actually sorted the list or not! – Joe Z. – 2013-12-28T01:27:25.887

    3

    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]);
        }
    }
    

    Darren Stone

    Posted 2013-12-27T09:17:45.597

    Reputation: 5 072

    3

    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

    Justin

    Posted 2013-12-27T09:17:45.597

    Reputation: 19 757

    3

    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.

    Petr Pudlák

    Posted 2013-12-27T09:17:45.597

    Reputation: 4 272

    2

    literal interpetation:

    echo "the array sorted. Could you please give the code?"

    Chaim Geretz

    Posted 2013-12-27T09:17:45.597

    Reputation: 129

    2

    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.

    darkflame

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    2

    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.

    Radiodef

    Posted 2013-12-27T09:17:45.597

    Reputation: 2 414

    2

    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.

    greggo

    Posted 2013-12-27T09:17:45.597

    Reputation: 231

    2

    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

    hdante

    Posted 2013-12-27T09:17:45.597

    Reputation: 181

    2

    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'
    

    hdante

    Posted 2013-12-27T09:17:45.597

    Reputation: 181

    Looks nice, but you could please explain it? – Victor Stafusa – 2013-12-28T01:33:37.350

    The question is misinterpreted as an algorithm that receives two arrays and returns 'Sorted array: etc' if the second is a sorted version of the first, or error otherwise. To the user I would explain that this code would allow him to be sure that his array was sorted. There's a bonus useless sorted(test) call to increase confusion. – hdante – 2013-12-28T01:59:21.757

    2

    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?
    

    John

    Posted 2013-12-27T09:17:45.597

    Reputation: 121

    2

    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();
    
        }
    }
    

    foota

    Posted 2013-12-27T09:17:45.597

    Reputation: 146

    2

    Plain trolling:

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

    Just implement it in the gym

    hdante

    Posted 2013-12-27T09:17:45.597

    Reputation: 181

    2

    ...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.

    sf13579

    Posted 2013-12-27T09:17:45.597

    Reputation: 101

    2

    // 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.

    a1kmm

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    2

    /* 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).

    a1kmm

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    2

    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()
    

    zephjc

    Posted 2013-12-27T09:17:45.597

    Reputation: 21

    2

    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]);[]
    

    kassens

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    2

    # 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.

    Joe Tannenbaum

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    2

    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: ")
    

    Arya

    Posted 2013-12-27T09:17:45.597

    Reputation: 131

    2

    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]
    

    Garret Raziel

    Posted 2013-12-27T09:17:45.597

    Reputation: 11

    2

    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;
    }
    

    Moto7451

    Posted 2013-12-27T09:17:45.597

    Reputation: 11

    2

    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!

    Coffee Maker

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    This is a bogosort, for those who are unaware. – Justin – 2013-12-30T05:04:44.683

    2

    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);
    

    urban

    Posted 2013-12-27T09:17:45.597

    Reputation: 11

    2

    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);
        }
    }
    

    user150878

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    2

    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;
            }
        }
    }
    

    Jay Haybatov

    Posted 2013-12-27T09:17:45.597

    Reputation: 101

    2

    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!");
                }
            }
        }
    }   
    

    Cannonball7171

    Posted 2013-12-27T09:17:45.597

    Reputation: 11

    2

    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;
    }
    

    nickguletskii

    Posted 2013-12-27T09:17:45.597

    Reputation: 131

    2

    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());
    }
    }
    

    Araejay

    Posted 2013-12-27T09:17:45.597

    Reputation: 21

    2

    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]);
        }
    }
    

    Stefan

    Posted 2013-12-27T09:17:45.597

    Reputation: 11

    You'll be sorting them in the wrong order, though. Negative numbers will come after positive ones. – Joe Z. – 2013-12-28T18:42:56.107

    2

    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.

    cooper667

    Posted 2013-12-27T09:17:45.597

    Reputation: 121

    2

    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;
            }
        }
    
    }
    

    Exoit

    Posted 2013-12-27T09:17:45.597

    Reputation: 21

    Your code is quite complex. Could you please explain it? – Victor Stafusa – 2013-12-30T05:33:59.673

    2

    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.

    Sumurai8

    Posted 2013-12-27T09:17:45.597

    Reputation: 161

    2

    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.

    Jack

    Posted 2013-12-27T09:17:45.597

    Reputation: 181

    1+1 for using a marquee – Charlie – 2014-01-02T04:56:50.097

    2

    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
    

    Konrad Borowski

    Posted 2013-12-27T09:17:45.597

    Reputation: 11 185

    2

    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;
    }
    

    Konrad Borowski

    Posted 2013-12-27T09:17:45.597

    Reputation: 11 185

    2

    PHP

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

    huehuehue

    Randomize the array until it's luckily sorted.

    user16229

    Posted 2013-12-27T09:17:45.597

    Reputation:

    1

    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]]]
    

    alephalpha

    Posted 2013-12-27T09:17:45.597

    Reputation: 23 988

    1

    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.

    Qantas 94 Heavy

    Posted 2013-12-27T09:17:45.597

    Reputation: 150

    1

    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.

    11684

    Posted 2013-12-27T09:17:45.597

    Reputation: 121

    Did you meant scanf("%d", &len); instead? – Victor Stafusa – 2013-12-27T20:57:22.237

    I edited this typo, but made a typo in the edit description. Doh. Thank you for pointing it out, nonetheless. @Victor – 11684 – 2013-12-28T08:56:11.260

    1

    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.

    Kyle Kanos

    Posted 2013-12-27T09:17:45.597

    Reputation: 4 270

    1

    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"}]
    

    Yves Klett

    Posted 2013-12-27T09:17:45.597

    Reputation: 251

    1

    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);
    

    Dom Hastings

    Posted 2013-12-27T09:17:45.597

    Reputation: 16 415

    1

    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.

    Xodarap

    Posted 2013-12-27T09:17:45.597

    Reputation: 241

    1You could improve that by creating a code that actually imports sat4j and runs it. – Victor Stafusa – 2013-12-28T01:32:47.677

    1

    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.

    a1kmm

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    1

    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.

    user10766

    Posted 2013-12-27T09:17:45.597

    Reputation:

    1

    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.

    user2951302

    Posted 2013-12-27T09:17:45.597

    Reputation: 150

    1

    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()
    

    hdante

    Posted 2013-12-27T09:17:45.597

    Reputation: 181

    1

    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!

    meiamsome

    Posted 2013-12-27T09:17:45.597

    Reputation: 161

    1

    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
    

    Contravariant

    Posted 2013-12-27T09:17:45.597

    Reputation: 101

    1

    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"))
      }
    }
    

    RC James Harlow

    Posted 2013-12-27T09:17:45.597

    Reputation: 11

    1

    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
    

    Alex

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    1Note that you could also simply write: printpi(). This code will also output the correct result. Eventually. – Alex – 2013-12-28T06:25:55.770

    1

    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);
    });
    

    kassens

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    Note that this does not work if more than 1 number is less than 4. – Qantas 94 Heavy – 2013-12-28T07:01:14.753

    This algorithm should get you most of the way there. It might happen that numbers close to each other have to be fixed by hand. In order to support some negative numbers, we can add a constant value to the second argument of setTimeout. – kassens – 2013-12-28T07:07:39.470

    1

    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';
    

    Mohsen

    Posted 2013-12-27T09:17:45.597

    Reputation: 677

    1

    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.

    Damon Swayn

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    1

    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
    

    Konrad Borowski

    Posted 2013-12-27T09:17:45.597

    Reputation: 11 185

    1

    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.

    Justin

    Posted 2013-12-27T09:17:45.597

    Reputation: 19 757

    1

    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.

    Patrick DeHaan

    Posted 2013-12-27T09:17:45.597

    Reputation: 11

    1

    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]
    

    Meta

    Posted 2013-12-27T09:17:45.597

    Reputation: 101

    1

    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.

    shiona

    Posted 2013-12-27T09:17:45.597

    Reputation: 2 889

    1

    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))))))))
    

    protist

    Posted 2013-12-27T09:17:45.597

    Reputation: 570

    +1 for using a Lisp variant. Is that Scheme? – Bob Jarvis - Reinstate Monica – 2014-01-02T03:37:33.000

    @BobJarvis Common Lisp :p – protist – 2014-01-04T10:11:52.463

    1

    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...

    Nercury

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    1

    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>
    

    Nercury

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    1

    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");
    }
    

    growlingoctopus

    Posted 2013-12-27T09:17:45.597

    Reputation: 11

    1

    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?

    Joey

    Posted 2013-12-27T09:17:45.597

    Reputation: 12 260

    1

    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.

    user11680

    Posted 2013-12-27T09:17:45.597

    Reputation: 1

    1

    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()
    }
    

    deniska

    Posted 2013-12-27T09:17:45.597

    Reputation: 11

    1

    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)]))
    

    eclectus

    Posted 2013-12-27T09:17:45.597

    Reputation: 1

    1

    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.

    wei2912

    Posted 2013-12-27T09:17:45.597

    Reputation: 121

    1

    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)
            }
        }
    }
    

    justinhj

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    1

    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.

    user3142682

    Posted 2013-12-27T09:17:45.597

    Reputation: 11

    1

    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.
    

    donutdan4114

    Posted 2013-12-27T09:17:45.597

    Reputation: 259

    Where to pass list of numbers? Is integer only? – Emil Vikström – 2013-12-29T11:58:27.463

    @EmilVikström - You run it through command-line and pass list of numbers to the script like I showed... – donutdan4114 – 2013-12-29T17:05:42.540

    1

    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.

    sh1

    Posted 2013-12-27T09:17:45.597

    Reputation: 121

    1

    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!

    Bob Jarvis - Reinstate Monica

    Posted 2013-12-27T09:17:45.597

    Reputation: 544

    1

    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.

    AJMansfield

    Posted 2013-12-27T09:17:45.597

    Reputation: 2 758

    1

    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.)

    Dan the Man

    Posted 2013-12-27T09:17:45.597

    Reputation: 141

    0

    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]
    

    hdante

    Posted 2013-12-27T09:17:45.597

    Reputation: 181

    0

    Shell Script

    #!/bin/sh
    echo "Enter your input, one number a line. Press Ctrl-d when you are done." >&2
    sort -n
    

    Damkerng T.

    Posted 2013-12-27T09:17:45.597

    Reputation: 171

    0

    Python

    print "the array sorted"
    

    Amir Rachum

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    7boring ... you can do better than that. – hildred – 2013-12-28T17:36:12.743

    0

    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)
    

    Vatine

    Posted 2013-12-27T09:17:45.597

    Reputation: 161

    0

    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
    

    Abhijit

    Posted 2013-12-27T09:17:45.597

    Reputation: 2 841

    0

    PYTHON

    myArray = [0.2, 1.7534, 0.63, 12.435, 23.0, 7.6, 8.2, 0.7, 3.9]
    myArray.sort()
    print(myArray)
    

    Oliver Ni

    Posted 2013-12-27T09:17:45.597

    Reputation: 9 650

    This code-trolling challenge requires your answer to be "utterly useless in practice." I find your answer to be useful and practical. Thumbs down. – Darren Stone – 2014-01-01T21:38:12.063

    -1

    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

    user97697

    Posted 2013-12-27T09:17:45.597

    Reputation: 111

    2

    Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and possibly provide the link for reference.

    – John Dvorak – 2013-12-28T23:11:49.493