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

  • Note: This question was severely edited since I first posted it here. The rules were moved to here, read them before posting any answer to understand the purpose of this. This was the first question created in the category.

    Imagine a lazy user on Stack Overflow asks this question:

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

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

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

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

    Rules can be found at tag description.

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

    Are you also allowed to use other languages than C?

    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.

    OK, thanks. I just wanted to know whether I could use C#.

    “Crazy language”? I think the expression you are looking for is _esoteric language_.

    @ProgramFOX I edited the question to clarify your point.

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

    hmm... using code from this question and sorting the result?

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

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

    Isn't better to just post the link to good resource, where he/she could learn something ? Instead wasting his/her time and trolling ?

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

    "The idea of this category is..." - it seems like this belong on the tag wiki, not in the question itself.

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

    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.

    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.

    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

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

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

    At this rate, you might get the second *ever* Great Question badge on this site :-D

    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.

    Wow, this question's about to get 100 upvotes and 10,000 views in less than 24 hours!

    @JoeZ. Yeah, I could not even dream about that before. Totally awesome. I am very pround of this and would like to thank everybody.

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

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

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

    This is definitely the first question I have ever seen that has more than 100 answers.... Is this good or bad?

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

    It's not "give-me-dah-codez", it's "plzsendtehcodz"!

    There should be some (manually awarded) badge for giving this type of answer - like `Sheldon Cooper` badge.

    Wow, there are 6 questions from this site on the hot questions list, and 5 of them are [tag:code-trolling]

    @Quin Ahahaha, not sure if that's great or... XD

    This is like Photoshop Trolling. Warning: hilarious.

    Explanation of a new class of questions should have gone on meta first and then migrated to the tag wiki once something was settled.

    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.

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

    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

    Wow, this now has 2^8 upvotes!

    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.

  • AShelly

    AShelly Correct answer

    7 years ago

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

    almost all the advice is wrong, and it simply keeps asking for the input list until you enter it already sorted.

    +1, for `1st, 2th, 3th, 4th...` and the downto operator--very advanced C programing techniques.

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

    `i==1?"st":"th"` hahaha...

    Java is not a scripting language...

    Java has garbage collection. Therefore Java is for "scripting", not real programming. That's basic CS101. (so says the troll.)

    @AShelly this is perfect, has all the nuanced hallmarks of the self-taught know-it-all C lifer.

    Good thing you remembered to put the `calloc` parameters in the right order! It creates such hard-to-find bugs when they are mixed up.

    You 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

    What is this line doing? Tokenizing the first value from the line? `sscanf( input, "%s", &input[0] )`

    I love this entire thing, but +1 for the `i==1?"st":"th"` and "scripting in Java" troll comment ;)

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

    I really do not want to accept my own answer. So, I will wait a bit more to see if this answer eventually beats it.

    Now I am going to want `until` every time I have to use `while (!condition)`

    @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, 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 One man’s madness is the previous one’s job security. The more I look at your answer, the more I like it.

    Telling a new programmer to use `atol()` - that's just _mean_ :P

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

    That's actually a little too close to home for what many Java coders would consider an acceptable match of solution to spec!!

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

    Not enough abstraction here. You need at least 10 interfaces, 20 implementations, enums, unit tests, coverage tests, Maven, integration tests, mocks...

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

    @NaftuliTzviKay We should create a MySQLSortEnterpriseEdition to implement your idea. Will Victor agree to GPL-license the code here so we can get started?

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

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

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

    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 Except if this is a homework about developing sorting algorithms, which should have nothing to do with databases.

    Surely this will actually be faster than a fully-Java implementation?

    Why not to give SQL query as solution itself?

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

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

    We can read the data from XML with some complex xml library before inserting into database.

    I'd prefer MariaDB.

    This isn't international, I don't see a LANGUAGES table.

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

    Lol, ListSort Enterprise Edition© :-P +1

    +1 for crazy overcoding. I suggest you break your answer into 3 or more 'module' answers so that I may +1 them individually

    And the cherry on top is that it's actually using a library sort:) It's completely to the spec, and completely useless

    Oh My God. Overkill indeed.

    Can we please reuse this freely for _all_ questions?

    @SimonT, We might, It sure is extensible enough.

    That... was... beautiful.

    You spent a lot of time for this trolling. Bravo! I'm impressed... +1

    You should package this on NuGet to see how many people actually check what they're using. :)

    Introducing a proper DI framework would help you getting rid of all those factories.

    Using DI will just confuse the OP, as this is just a quick example.

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

    SimonT, it's Creative Commons so just give proper attribution ;-)

    Is it bad that this is what I consider to be the typical non-joke Java enterprise code to look like?

    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`, `IArrayProcessor`, and `IArrayWriter`, along with the mind-bending reflection code to accompany it.

    @Aaronaught, nah, that might be actually useful. A IDoubleArrayFactoryManager might be a more generic approach, how that I think of it.

    That's sooooo evil. And, because of that, beautiful

  • Even more literal interpretation:

    echo " aaehrrty"
    

    that is, "the array" sorted.

    I came here to post this.

    save as file `sort.sh` and call as `sh sort.sh "an array of doubles"`

    I think you missed the "the user inputs an array of doubles".

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

  • 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([email protected]{$_[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.

    evil! evil! evil!

    about as decipherable as any other Perl script to me :)

    Brilliant! This is probably the most intimidating to a newcomer.

    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 Actually, `$_` is an empty string at that point. I stored my desired output in `$\ `, which is the output record separator.

    Brilliant. Never would have considered using `$\\` as a side effect. +1

    I would love to see the professor's comments upon the student turning this in as his/her homework.

    @Andy simple. "How does it work?"

    and all user-created variables have pretty names that follow all thinkable conventions

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

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

    Hehe, this one actually made me laugh out loud. Anyway, I agree that a little better explanation would be helpful.

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

    Wow, that's evil all right.

    @Bakuriu, that was a typo, although it would make good troll as well. But I figure one troll per answer, so I fixed it.

    Why not just import someoneElsesDoubleArraySorter, and just have it work magically?

    A `O(n)` sort algorithm. Nice.

  • 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 [email protected]; 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 [email protected];do echo $(sleep $i)$i&done;wait
    

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

    5. It only works on _GNU/Linux_, due to use of `/proc/cpuinfo`.

    Extremely creative solution, by the way :)

    This is amazing. I can't even express how awesome that is. I'm considering using that actively, because WHY NOT.

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

    -1 for using bash instead of /bin/sh :)

    6. It counts hyperthreading cores, not physical cores.

    And of course: 7. Concurrency issues! Numbers below or close to 0.0 may be printed before the friendly prompt. 8. Negative numbers gives errors.

    @kps11346, `/proc/cpuinfo` is in cygwin of all things, so this is cross-platform portable code!

    This solution made me LOL. Great job!

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

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

    That's even better because it's a built-in function.

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

    I particularly like how this doesn’t *actually* use jQuery.

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

    Too bad that I can't upvote twice. It is brilliant how you could be so evil in so many different aspects.

    Write this code was really fun!

    The "tricky part" is elegant. OP, strive to have that kind of code structure someday.

    That F'n doble "validation" LOOOOOOOOOOOOL omg omg day made! edited for less caps

    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.

    For a guy (OP) who doesn't even know how to sort an array, I would be surprised if he could easily do anything =)

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

    Or a "script": `#!/usr/bin/sort`.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM