276
votes
\$\begingroup\$

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.

\$\endgroup\$
30
  • 48
    \$\begingroup\$ Stack Oversort \$\endgroup\$ Dec 27, 2013 at 13:26
  • 6
    \$\begingroup\$ @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. \$\endgroup\$
    – IQAndreas
    Dec 27, 2013 at 16:21
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ Dec 27, 2013 at 17:14
  • 18
    \$\begingroup\$ 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! \$\endgroup\$
    – SimonT
    Dec 28, 2013 at 4:21
  • 4
    \$\begingroup\$ I'm surprised no one has offered a solution based on sleep sort yet \$\endgroup\$ Dec 28, 2013 at 11:02

141 Answers 141

2
votes
\$\begingroup\$

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

}
\$\endgroup\$
2
votes
\$\begingroup\$

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.
\$\endgroup\$
1
  • 1
    \$\begingroup\$ This is even funnier because quicksort in Haskell is like three lines. \$\endgroup\$
    – wchargin
    Dec 27, 2013 at 21:27
2
votes
\$\begingroup\$

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.

\$\endgroup\$
2
votes
\$\begingroup\$

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

\$\endgroup\$
2
votes
\$\begingroup\$

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?
\$\endgroup\$
2
votes
\$\begingroup\$

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'
\$\endgroup\$
2
  • \$\begingroup\$ Looks nice, but you could please explain it? \$\endgroup\$ Dec 28, 2013 at 1:33
  • \$\begingroup\$ 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. \$\endgroup\$
    – hdante
    Dec 28, 2013 at 1:59
2
votes
\$\begingroup\$

Plain trolling:

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

Just implement it in the gym

\$\endgroup\$
2
votes
\$\begingroup\$

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

\$\endgroup\$
2
votes
\$\begingroup\$
// 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.

\$\endgroup\$
2
votes
\$\begingroup\$
/* 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).

\$\endgroup\$
2
votes
\$\begingroup\$

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]);[]
\$\endgroup\$
2
votes
\$\begingroup\$
# 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.

\$\endgroup\$
2
votes
\$\begingroup\$

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: ")
\$\endgroup\$
2
votes
\$\begingroup\$

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]
\$\endgroup\$
2
votes
\$\begingroup\$

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;
}
\$\endgroup\$
0
2
votes
\$\begingroup\$

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);
\$\endgroup\$
2
votes
\$\begingroup\$

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;
        }
    }
}
\$\endgroup\$
2
votes
\$\begingroup\$

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()
\$\endgroup\$
2
votes
\$\begingroup\$

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;
}
\$\endgroup\$
2
votes
\$\begingroup\$

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.

\$\endgroup\$
2
votes
\$\begingroup\$

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]);
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ You'll be sorting them in the wrong order, though. Negative numbers will come after positive ones. \$\endgroup\$
    – Joe Z.
    Dec 28, 2013 at 18:42
2
votes
\$\begingroup\$

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.

\$\endgroup\$
2
votes
\$\begingroup\$

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.

\$\endgroup\$
2
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ +1 for using a marquee \$\endgroup\$
    – Charlie
    Jan 2, 2014 at 4:56
2
votes
\$\begingroup\$

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
\$\endgroup\$
2
votes
\$\begingroup\$

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;
}
\$\endgroup\$
2
votes
\$\begingroup\$

PHP

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

huehuehue

Randomize the array until it's luckily sorted.

\$\endgroup\$
2
votes
\$\begingroup\$

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.

\$\endgroup\$
2
votes
\$\begingroup\$

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

    }
}
\$\endgroup\$
2
votes
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ This is a bogosort, for those who are unaware. \$\endgroup\$
    – Justin
    Dec 30, 2013 at 5:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.