Take the tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question
33  
Stack Oversort –  ThiefMaster Dec 27 '13 at 13:26
5  
@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 Dec 27 '13 at 16:21
4  
Yay! First on hot network questions list again! Enough of good challenges like this and we might make it out of beta soon :-D –  Doorknob of Snow Dec 27 '13 at 18:35
6  
@Matthew For fun! We're on the code golf site, and this is great to just enjoy coding (and take out frustration on the hundreds of users on SO who ask these kinds of questions daily :-P) –  Doorknob of Snow Dec 27 '13 at 22:16
10  
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! –  SimonT Dec 28 '13 at 4:21
show 36 more comments

135 Answers

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

share|improve this answer
1  
It would be cool to write a program that writes this program. –  Alexey Lebedev Dec 28 '13 at 23:14
add comment

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);
}
share|improve this answer
 
This is incredible. –  Trevor Alexander Dec 29 '13 at 0:23
 
@TrevorAlexander It was much more of a pain to code than I expected. C really doesn't handle polymorphism well. –  Alex Becker 23 hours ago
add comment

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.

share|improve this answer
add comment

literal interpetation:

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

share|improve this answer
add comment

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]]]
share|improve this answer
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

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'
share|improve this answer
 
Looks nice, but you could please explain it? –  Victor Dec 28 '13 at 1:33
 
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 Dec 28 '13 at 1:59
add comment

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

}

}

share|improve this answer
add comment

Plain trolling:

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

Just implement it in the gym

share|improve this answer
add comment

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

share|improve this answer
add comment
// 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.

share|improve this answer
add comment

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]);[]
share|improve this answer
add comment
# 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.

share|improve this answer
add comment

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: ")
share|improve this answer
add comment

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]
share|improve this answer
add comment

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!

share|improve this answer
 
This is a bogosort, for those who are unaware. –  Quincunx yesterday
add comment

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;
        }
    }
}
share|improve this answer
add comment

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!");
            }
        }
    }
}   
share|improve this answer
add comment

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());
}
}
share|improve this answer
add comment

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()
share|improve this answer
add comment

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]);
    }
}
share|improve this answer
 
You'll be sorting them in the wrong order, though. Negative numbers will come after positive ones. –  Joe Z. Dec 28 '13 at 18:42
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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"}]
share|improve this answer
add comment

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);
share|improve this answer
 
+1 for "magic sorting algorithm" –  Victor Dec 28 '13 at 0:10
add comment

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.

share|improve this answer
1  
You could improve that by creating a code that actually imports sat4j and runs it. –  Victor Dec 28 '13 at 1:32
add comment

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?
share|improve this answer
add comment

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.

share|improve this answer
add comment

protected by Doorknob of Snow Dec 28 '13 at 21:39

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

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