Take the 2-minute 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.

Given an integer array, write a program that determines if it is sorted in ascending order.

Remember that this is a code trolling question.

I am looking for most interesting ways that people come up with.

The answer with most upvotes wins.

This question is inspired by a 'creative' solution that a candidate gave me in an interview :)


The 'creative' solution was something like this:

  • Because for a sorted array

    • all the elements on the left side of any element must be smaller
    • all the elements on the right side of any element must be bigger

Therefore, run a main loop for all elements and check the above two conditions by running two nested loops inside the main one (one for left side and one for right side)

I was shocked!!.

share

locked by Doorknob May 10 at 16:12

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

58  
This is not a duplicate. Some moderators feel it necessary to mark every question duplicate to others without reading it. This is not a sorting question at all. Read it. –  microbian Feb 27 at 17:16
3  
At the end of the contest I would like to know the "creative" solution, too! :) –  Vereos Feb 27 at 17:23
16  
@micro Diamond moderators are community elected. You are confusing moderators with the privilege system. –  Doorknob Feb 27 at 17:58
3  
@microbian So have you hired that guy? –  VisioN Feb 28 at 8:17
3  
If only StackExchange API allowed write access, I'd ask the question "Is this array sorted?" and count upvotes on positive/negative answers.. –  Michael Foukarakis Mar 1 at 8:31

69 Answers 69

up vote 78 down vote accepted

Ruby

Everyone knows: sorting is very slow and takes many cycles (the best you can do is something with n log(n)). Thus it is quite easy to check if the array is sorted. All you have to do is compare the runtime of sorting the array and sorting the sorted array.

array = [1, 5, 4, 2, 3]

## measure the time needed to sort the array 1m times
tstart = Time.now
1000000.times {
  array.sort
}
trun = Time.now - tstart

## now do a reference measurement on a sorted array
array.sort!
tstart = Time.now
1000000.times {
  array.sort
}
treference = Time.now - tstart

## compare run times
if trun > treference
  print "array was not sorted"
else
  print "array was sorted"
end
share
5  
wow wow wow! :) –  microbian Feb 27 at 17:49
19  
This depends on the sorting algorithm though. Merge sort or heap sort would not show any difference at all, independent of whether the array is already sorted or not. –  Niklas B. Feb 27 at 19:17
4  
@NiklasB. Ruby uses quicksort. That said this method could get tricky and give false positives when the input array is almost sorted, or, more likely, false negatives when the array is sorted (it would be very unlikely for treference <= trun for every sorted case, just due to nondeterministic other stuff). In theory it seems like you'd get about 50% false negatives for the sorted case? –  Jason C Feb 28 at 3:14
6  
Interesting thought but not deterministic. Its about as good as one could do ten push ups and then ten more push ups and then decide if the first array was sorted or not because one sweated more on the second set of push ups. Did we forget, we run code on multi-tasking machines? Also on very small arrays, the time slice is simply not accurate enough. +1 for a wild attempt though! –  LMSingh Feb 28 at 7:58
3  
@JasonC - it's worth noting that this makes the implementation above even more dubious: it relies not only on the knowledge that ruby's internal sorting algorithm is quicksort (which is in itself undocumented and therefore a dubious thing to rely upon) but that the specific implementation is optimized for the case of already-sorted data (which quicksort by default is not: quicksort is only O(n log n) on average case... its worst case performance is O(n^2) and in a naive implementation that worst case is actually being called on already-sorted data). –  Jules Mar 5 at 8:26

Javascript

array = prompt("Give the array");
while (true) {
    sorted = prompt("Is it sorted?");
    if (/yes|Yes/.test(sorted)) {
        alert("The array is sorted.");
        break;
    } else if (/no|No/.test(sorted)) {
        alert("The array is not sorted.");
        break;
    } else {
        alert("Dear user:\n\nPlease refer to the manual (RTFM) to observe how to use the system accordingly to the defined business rules.\nNow, try again.");
    }
}
share
3  
+1 for this. I LOL'ed!! –  stackErr Feb 27 at 20:17
55  
-1 not enough JQuery. –  Pierre Arlaud Feb 28 at 14:09
3  
I had a similar idea that would ask for the array, and then one by one prompt "is this bigger than this?" And if all are true, then the array is sorted –  SirBraneDamuj Feb 28 at 15:03

Java - Recursive Subsets

Welcome to Stack Overflow! This is an excellent first question, as it stumps even some veteran coders. Let me give you a bit of background information before I just hand out the code:

Determining sortedness can be a difficult task at first glance. For any set of length n, there are n! possible ways of ordering it. These are called permutations. If your array has distinct elements, only one of those possibilities is sorted! To find the sorted one, you have to sift through them all until you find the right (possibly only) one, discarding all the others.

What? Surely it isn't that hard...

Algorithms with n! complexity take a long time for larger inputs, but with a bit of work we can get around that, and move down a whole order of complexity. That's still exponential time, but it's much better than factorial.

To do this, we only need consider the following mathematical fact: If an array is sorted, then every one of its (relatively ordered) subsets is sorted as well. You can ask the experts over at Mathematics for a formal proof, but it's intuitively true. For instance, for the set 123, the proper subsets are 1 2 3 12 13 23. You can see they are all ordered. Now if the original was 213, you'd have 2 1 3 21 23 13, and right away you can see that 21 is out of order.

The reason this is important is because there are far fewer than n! subsets. In fact, there are only 2n-2 subsets we need to look at. We can exclude the set containing the entire array of original numbers, as well as the empty set.

Still, 2n-2 can be a lot of work. As with most things that exceed polynomial time, a divide-and-conquer approach works well here. The simplest approach? Recursion!

The basics steps are simple. For every subset of your input, you generate smaller subsets. Then for each of those, you do the same thing. Once your subsets are down to size 2, you simply check which one is bigger. Since you shrink the size of the subsets each time, it actually goes quicker than you'd expect.

The key fact here is that you can exit early, as soon as you find a single subset out of order. You don't have to search through them all. If one is bad, the whole group is bad. This is a speed consideration you don't see in a lot of these other answers.

Enough talk, let's have the code!

I've done this in Java since it's a popular language and easy to read. The elegance of the recursion should be apparent:

import java.util.ArrayList;

public class SortChecker {

    static final Integer[] input = {1, 2, 3, 4, 5};

    public static void main(String[] args) {
        if(isSorted(input))
            System.out.println("The array is sorted properly.");
        else
            System.out.println("The array was not sorted properly.");
    }

    public static boolean isSorted(Integer[] in){
        if(in.length == 1)
            return true;
        if(in.length == 2)
            return (in[0] <= in[1]);
        ArrayList<Integer[]> subsets = getSubsets(in);
        for(Integer[] next : subsets){
            if(!isSorted(next))
                return false;
        }
        return true;
    }

    public static ArrayList<Integer[]> getSubsets(Integer[] in){
        ArrayList<Integer[]> subsets = new ArrayList<Integer[]>();
        int bitmasks = (1 << in.length) - 1;
        for (int i = 1; i < bitmasks; i++){
            ArrayList<Integer> subset = new ArrayList<Integer>(); 
            for (int j = 0; j < in.length; j++)
                if ((i & (1 << j)) > 0) 
                    subset.add(in[j]);          
            subsets.add(subset.toArray(new Integer[1]));
        }
        return subsets;
    }
}

For the record, I got bored and killed it after waiting 15 minutes for a sorted 12-element array. It'll do 11 elements in about 45 seconds. Of course, it really does exit earlier for non-sorted, so that's, um, good.

Update: On a fresh reboot, it does 12 elements in 13 minutes. 13 takes almost 3 hours, and 14 is at 20 hours and counting.

share
8  
+1 this is probably the least efficient algorithm I've ever seen. Should be around O(n!*2^(n!))-Complexity (probably worse). –  Ral Zarek Feb 28 at 11:35
6  
I'm sure I've seen worse, but it is pretty bad. I half-heartedly tried to determine complexity, but gave up and called it O(big). –  Geobits Feb 28 at 13:55
1  
Providing a solution that is less efficient then even the naive attempt of the travelling salesman problem is impressive! –  recursion.ninja Mar 1 at 17:56
3  
As the chance of a 12 element array being sorted is only 1 in 479 million, it really doesn't matter that it takes a while to be absolutely certain that one is, surely? You're never actually likely to see one in the real world... –  Jules Mar 3 at 20:07
2  
@Geobits No problem. Run Victor's algorithm and answer "yes" at the first prompt. –  Jason C Mar 5 at 14:12

C++ - a brute force method

Everybody knows that brute force methods are always the fastest.

bool issorted(std::vector<int>& list)
{
  switch (list.size()) {
    case 0: case 1: return true;
    case 2: return list[0]<=list[1];
    case 3: return list[0]<=list[1] && list[1]<=list[2];
    case 4: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3];
    case 5: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4];
    case 6: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5];
    case 7: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6];
    case 8: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7];
    case 9: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8];
    case 10: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9];
    case 11: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10];
    case 12: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11];
    case 13: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12];
    case 14: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13];
    case 15: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14];
    case 16: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15];
    case 17: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16];
    case 18: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17];
    case 19: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18];
    case 20: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19];
    case 21: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20];
    case 22: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21];
    case 23: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22];
    case 24: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23];
    case 25: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24];
    case 26: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25];
    case 27: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26];
    case 28: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27];
    case 29: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28];
    case 30: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29];
    case 31: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30];
    case 32: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31];
    case 33: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32];
    case 34: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33];
    case 35: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34];
    case 36: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35];
    case 37: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36];
    case 38: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37];
    case 39: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38];
    case 40: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39];
    case 41: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40];
    case 42: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41];
    case 43: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42];
    case 44: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43];
    case 45: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44];
    case 46: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45];
    case 47: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46];
    case 48: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46] && list[46]<=list[47];
    case 49: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46] && list[46]<=list[47] && list[47]<=list[48];
    case 50: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46] && list[46]<=list[47] && list[47]<=list[48] && list[48]<=list[49];
    case 51: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46] && list[46]<=list[47] && list[47]<=list[48] && list[48]<=list[49] && list[49]<=list[50];
    case 52: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46] && list[46]<=list[47] && list[47]<=list[48] && list[48]<=list[49] && list[49]<=list[50] && list[50]<=list[51];
  }
}

The actual routine is longer (it goes to std::npos), but I'm limited to 30000 characters in posting here.

share
    
I really like this. –  Jakob Mar 3 at 10:23
3  
This is like the "use every part of the buffalo" approach to case statements. –  Jonathan Van Matre Mar 3 at 13:48
    
This is awesome. Unroll all the loops! –  McKay Mar 4 at 14:45
    
great thought!!! –  bikram990 Apr 30 at 9:01

Inform

Inform is a language for writing interactive fiction games for the classic Infocom Z-machine interpreter. To avoid spoilers, I'm giving the results of my program first, then the source code.

Edit: I made a small revision to allow adding numbers to the array, and included a charming room description.

Sorted
An Interactive Fiction by Jonathan Van Matre
Release 1 / Serial number 140301 / Inform 7 build 6G60 (I6/v6.32 lib 6/12N) SD

Sorting Room
You are in the Sorting Room, a sterile expanse of pure white. Translucent
lucite walls leak a lambent clinical light into the spotless room.

You can see a safe (closed), a flask of poison, a radioactive isotope 
attached to a radiation detector that triggers a hammer, an array (empty) 
and Erwin Schrodinger here.

>open safe
You open the safe.

>put flask in safe
(first taking the flask of poison)

You put the flask of poison into the safe.

>put isotope in safe
(first taking the radioactive isotope attached to a radiation detector 
 that triggers a hammer)

You put the isotope detector assembly into the safe, carefully placing 
the hammer next to the fragile glass of the flask of poison.

>get array
Taken.

>put numeral 1 in array
(first taking the numeral 1)

You put the numeral 1 into the array.

>put 2 in array
(first taking the numeral 2)

You put the numeral 2 into the array.

>put 3 in array
(first taking the numeral 3)

You put the numeral 3 into the array.

>examine array
In the array are a numeral 3, a numeral 2 and a numeral 1.

>put array in safe
You put the array into the safe.

>ask Erwin about whether the array is sorted
Erwin grumbles and complains, "You haven't finished the experiment" 

>close safe
You close the safe.

>ask Erwin about whether the array is sorted
Erwin beams and proudly announces, "Indeterminate!" 

And herewith the source code:

"Sorted" by Jonathan Van Matre

The Sorting Room is a room. "You are in the Sorting Room, a sterile expanse of pure white. Translucent lucite walls leak a lambent clinical light into the spotless room."
The safe is a container. The safe is in the Sorting Room. The safe is openable. The safe is closed.
There is a flask of poison in the Sorting Room.
There is a radioactive isotope attached to a radiation detector that triggers a hammer in the Sorting Room.
There is an array in the Sorting Room. The array is a container.
There is a numeral 1 in the Sorting Room. The numeral 1 is undescribed.
There is a numeral 2 in the Sorting Room. The numeral 2 is undescribed.
There is a numeral 3 in the Sorting Room. The numeral 3 is undescribed.
There is a numeral 4 in the Sorting Room. The numeral 4 is undescribed.
There is a numeral 5 in the Sorting Room. The numeral 5 is undescribed.
There is a numeral 6 in the Sorting Room. The numeral 6 is undescribed.
There is a numeral 7 in the Sorting Room. The numeral 7 is undescribed.
There is a numeral 8 in the Sorting Room. The numeral 8 is undescribed.
There is a numeral 9 in the Sorting Room. The numeral 9 is undescribed.
In the Sorting Room is a man called Erwin Schrodinger.
Understand the command "ask" as something new.
Understand "ask [someone] about [text]" as asking it about.
After inserting the isotope into the safe:
    If the safe encloses the flask, say "You put the isotope detector assembly into the safe, carefully placing the hammer next to the fragile glass of the flask of poison.";
Instead of asking Erwin about something:
    If the safe is closed and the safe encloses the flask and the safe encloses the array and the safe encloses the isotope, say "Erwin beams and proudly announces, 'Indeterminate!' ";
    Otherwise say "Erwin grumbles and complains, 'You haven't finished the experiment' ";
share

Doge Ruby

First you must run this setup code

class Array;alias ruby sort;end
def self.method_missing x,*a;x;end
def very x;$a=x;end
def many x;$b=$a.send x;end
def wow;puts $a==$b;end

Then just store the array in a variable called coding and run:

  very coding

                 many ruby
so algorithm


      wow

And your answer will be printed (true or false).

Please also add the doge code for optimal performance:

#~! SET DOGE=1 PERFORMANCE=OPTIMAL ONERROR=nil PIC=
#                    ***=*                                                       
#                    **===*                                                      
#                    ***=-=&                                   &&**&             
#                    **==--=                                  ***===*            
#                   &***=---*                               $*=------*&          
#                   &***=---=*                             $**=----;;=&          
#                   &**==----=&                           &*===---;;;-*          
#                   &**==----=*                          &**=-==--;;;;=          
#                   ****=-----=*                       &&*==--=---;;;;-          
#                   **===------=&                     $&*==-------;;;;-          
#                   **===-------=*&$$                &*==------;;;;;;;-          
#                   **==----==-====***&&&&&&&&$$    &*==-;;---;;;;;;;;-&         
#                  &*=---=====================*******=---;---;;;;;;;-;;=         
#                  *=======*=========================---;;--;;;;;;;;;;;*         
#                  *===***=======================------;;--;;""""";;;;;=         
#                  *=*****========================;--;;;;--;;""""";;;;;*         
#                &*********====-----===============;;;;;----;"","";-;;-&         
#               ***********====----================-;;;;----;",,";;----          
#             &************===---====================-;;;;;;",,"";----=          
#            &*************===---=====================-;;;;",,,";-----*          
#            ******=*******===--=======================--;",,,"";-----&          
#           &**************==--=========================-;"","";----;-           
#          ****************==---====****=====-===========--;";;-;;;";=           
#         ****************==----==*******===--=============--;----;--=           
#        &*****=;"";==***===----==*******===----=============------;-=$          
#        &&&***;"",,"-**====---==********=====-===============----;;;-&          
#       &&&&&*=-;;";";*==========****=***======--=========***==---;;;-&          
#      $&&&&&&=="",,,-===**=======***==-;-=================**===--;;;;*          
#      &&&&&&&-="",,"==***==***======-",,,";=-===================--";;=          
#      &&&&&**=-""";==****=***===---;"-=-,,,"--===================-;;;=&         
#     &&&&&&***--;=***********=---;,,-*",,,,,"--==================--;--*         
#     &&&&&***=*=*************=-;;","=-,,,,,,"-====================----=$        
#    &&&&&&*******************==--","-;,,,,,"-====*****=============-===&        
#   $&&&&&&******************===---",";"""";=******************=====-===*        
#   &&&&&&&&&*****************======--;;--==********************=========&       
#  &&&&&&&&&&&******=**********===========*==*****&&************=========*       
#  &&&&&&&&*=---;--==**********==============*********************=======*&      
#  &&&&&&&-""""";;"";=**********==**=========*****&&&**************=======*      
# &&&&&&&*,,,,,,,,,,,"-****&************=*******&&&&&&&************========&     
# &&**&&&=,,,,,,,,,,,,;*&&&&***********************&&&&&&***********=======*     
# &&&*&&&*",,,,,,,,,,,;*&&&*************&&**********&**************========*&    
#&&&&&&&&-"",,,,,,,,,,-*&&&**********&**&&&&&&&******************==========**    
#&&&&&&&*=,,,,,,,,,,,"-***************&&&&&&&&&*****************====--======*&   
#&&***&&*=;,,,,,,,,,";=*==*****************&&&***************=======--=======&   
#*&&&&**=-;",,,,,,"";-=*********=**&*********&&**************=======--======**   
#&&&&&**=-""",,,,,"";==**==***===**********************======***===---=======*&  
#&&&&&**=-;"""""","";;=-===*======*********************==******====----======*&  
#*&&&&**=-;""""""""";=-============*****************==*********====---==--===**  
#&&&&&***=",,,,,,"""";--=============*******==****************====----=--====**& 
#&&&&&****"",,,,,,,,,;-=========--===****====******************====--==-======*& 
#&&&&&&&&*-"",,,,,,,,,"--==--;"""";====**===********************======--======** 
#&&&&&&***=-;",,,,,,,,,,,;",,,""";-=======********************===-------=======* 
#&&&&&&&****=;""""""""",,,"""";;--==**====*******************=====--------=====* 
# &&&&&&&***=-;;;;;;;;;"";;;;;---==***====*****************=====--=--------====*$
# &&&&&&*****=-;-----=--------=====*=======****************====-==---------=====&
#  &&&&&******==-==-=============***========*************======----=--------====&
#  &&&&************==========================***********=====----------------===*
#  $&&&&***************====================***********=*======-------------=--==*
#   &&*&************=====================**************======--------------=====*
#   &******************=================**************=========-----------======*
#    &***********=*****================************==========------;-------=====*
#    &*****************================***********=============---------========*
#     &*************===================**********==***========--------========***
#      **************==================********====**===*=====--------=======****
#      &************=============================*****=*=====--------=======*****
#       &****=*******=============================**============--=======*=******
#       $*****=====**===========================***===================**********&
#        &*****=====================-====-====*=*=====*=======--==***************
#         &*****===========---==--===============**=**=*========*****************
#          &*****====---=---------========********======***===*******************
#           *****=======-=-------======*******=**==****==*==*********************
#           $***======================******===**********************************
#            &***===================*******==***=******************************=&
#             &***=========-=========*************==***************************=&
#              ******===*=======*=*****************==*************************==&
#~! END

This is the easiest way.


(the ASCII art was generated by a script I wrote up, derived from this image.)

share
7  
You forgot "so algorithm". A real doge sample has 3 sentences before "wow". And yes, I'm very fun at parties. –  Pierre Arlaud Feb 28 at 14:12
    
@ArlaudPierre Heh, okay, fixed :P –  Doorknob Feb 28 at 14:15
11  
So comment, very improvement, many useful. Wow. –  Pierre Arlaud Feb 28 at 14:19
    
You should have written a BF program in ascii shaped like a doge... new question idea!! –  TheDoctor Feb 28 at 23:27

PHP

You'd love the easiness and straightforwardness of the following solution. The overall concept and the cutting edge functions used in this masterpiece of coding will immediately bring you up to the elite list of the top developers of the World.

function is_sorted($input) {
    mysql_connect('localhost', 'name', 'password');
    mysql_select_db('database');

    mysql_query('
        CREATE TEMPORARY TABLE sorting_table (
          `value` int NOT NULL
        )');

    foreach ($input as $value) {
        mysql_query('INSERT INTO sorting_table VALUES (' . $value . ')');
    }

    $i = 0;
    $result = 'SORTED';
    $query = mysql_query('SELECT * FROM sorting_table ORDER BY value ASC');
    while ($value = reset(mysql_fetch_row($query))) {
        if ($input[$i++] != $value) {
            $result = 'NOT SORTED';
            break;
        }
    }

    mysql_query('DROP TABLE sorting_table');

    return $result;
}

print is_sorted(array(10, 20, 30, 40, 50));
share
    
+1 Because you are using the same concept of my answer to the sorting question –  Victor Feb 27 at 18:48
4  
Would this work if Mrs. Roberts enters the values? –  user80551 Feb 28 at 5:15
3  
@user80551 yes because there is no table called students –  ratchet freak Feb 28 at 11:26
3  
@JonathanVanMatre Certainly security is one of the strongest sides of this code. –  VisioN Feb 28 at 14:53
1  
This is my new favourite answer on this website; but for extra marks I'd love to see you use a PDO for security –  a_programmer Apr 4 at 15:29

C# - The power of statistics

What you really need to do to solve this is to re-frame the question in a way that makes the solution obvious. Because this is basically a "true-false" type question, what you are essentially asking is "how can I be 100% certain that the array is sorted?" If one word pops out of that question, it is the word "certain". What is the best way to measure certainty? You got it: statistics.

Other answers here only check to see if the array is sorted in one direction. This solution tests both ascending and descending order at the same time. The trick is to take an array of the same size that you already know is sorted (easy to make one yourself) and then find out how well the ordering of each array correlates with the other one. Calculating the Kendall tau rank correlation coefficient is the easiest way to do this:

using System;

namespace Homework
{
    class Example
    {
        static void Main(string[] args)
        {
            int[] n1 = { 23, 50, 16, 57, 19, 60, 40, 7, 30, 54 };
            int[] n2 = { 7, 16, 19, 23, 30, 40, 50, 54, 57, 60 };
            int[] n3 = { 60, 57, 54, 50, 40, 30, 23, 19, 16, 7 };

            Console.WriteLine(isSorted(n1));
            Console.WriteLine(isSorted(n2));
            Console.WriteLine(isSorted(n3));
        }

        static string isSorted(int[] a)
        {
            double t = 0;
            int n = a.Length;

            //Build a 'known' sorted array.
            int[] k = new int[n];
            for (int i = 1; i < n; i++)
            {
                k[i] = i;
            }

            //Find the Kendall's tau coefficient.
            //First the numerator...
            for (int i = 1; i < n; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    t += Math.Sign(a[i] - a[j]) * Math.Sign(k[i] - k[j]);
                }
            }
            //...then the denominator.
            int d = n * (n-1) / 2;
            //This gives the correlation coefficient.
            double sortedness = t / d;
            //1 is perfect correlation (ascending), -1 is perfectly non-correlated (descending).
            if (Math.Abs(sortedness) == 1)
            {
                return "Sorted";
            }
            else
            {
                return "Unsorted";
            }
        }
    }
}

Output:

Unsorted
Sorted
Sorted

This function is also very easy to extend the functionality of, as it would be trivial to add functionality like "Mostly sorted" or "More sorted than not" or "Completely random".

Edit

Almost forgot to go over the efficiency of the algorithm. This is currently O(7). There is one in the method name, one in each of the "for" keywords, one in the "double" declaration, and two in the uses of the variable "sortedness". You can improve this all the way down to O(0) (which is as low as you can go) by renaming the function, changing the double to a decimal, disemvoweling "sortedness" to "srtdnss", and converting the for loops to while loops.

share
2  
I painstakingly recalculated the complexity and determined it to be O(8). You're handwaving away the output, which I believe should factor in. To have a truly O(7) complexity, you might consider returning "ascending"/"haphazard", instead of "sorted"/"unsorted". –  Geobits Mar 1 at 7:03
    
@Geobits - I looked at it again, and of course you are correct. I guess this shows that there is a minimum complexity of O(1) when returning the strings. This is a small price to pay though, because returning a boolean is twice as bad. –  Comintern Mar 1 at 16:24
1  
+1 for the O() calculation. -1 for not also calculating a Spearman rho, because aren't two correlations better than one? And +1 for stats in C#, the proven favorite of statisticians. –  Jonathan Van Matre Mar 3 at 14:03
    
Please tell me the O(7) thing is a joke –  mbatchkarov Mar 4 at 13:43
    
@mbatchkarov - It's little O notation. :-) –  Comintern Mar 4 at 14:53

Ruby

Following strategy will eventually reveal if an array is sorted:

  1. A be an array (either sorted or unsorted, e.g. [1,2,3] or [1,3,2])
  2. P be an array holding all permutations of A
  3. If A is sorted, it is either the maximum or minimum of P (which basically are the sorted versions of A in Ruby)

Online version for testing.

class Array
   def is_sorted?
      permutations = permutation.to_a
      self == permutations.max || self == permutations.min
   end
end
share
1  
I don't think I understand the explanation. If the array is, e.g., [1, 9, 100], then the min is 10019 and the max is 91100, but the sorted number is 19100. Playing with the online version, max is [100,9,1] and min is [1,9,100]. I don't see where anything is being "represented by a number"; it looks like the arrays are just being ordered lexicographically. This would be the same, I suppose, if all the numbers are just one digit. –  Joshua Taylor Feb 27 at 19:02
    
"...either the maximum or minimum..." loved it. –  microbian Feb 27 at 19:08
    
@JoshuaTaylor: Thanks for the heads-up! I wanted to explain it in an easily understandable way - which ended up being plain wrong ;) I corrected my description... –  David Herrmann Feb 27 at 21:15
2  
@JoshuaTaylor the ruby methods Array#max and #min select the largest and smallest element with regards to the < and > operators. On Arrays, < and > implement lexicographical sorting. [1,9,100] is the minima of all ordered permutations of 1, 9 and 100 in the lexicographic ordering. –  Karl Damgaard Asmussen Feb 28 at 0:13
    
That's almost production quality. –  primo Feb 28 at 4:03

C# - non-deterministic solution

This code probably works.

static bool isSorted(int[] s)
{
    var rnd = new Random();
    for (var i = 0; i < s.Length * s.Length * s.Length; i++)
    {
        var i1 = rnd.Next(0, s.Length);
        var i2 = rnd.Next(0, s.Length);
        if (i1 < i2 && s[i1] > s[i2] || i1 > i2 && s[i1] < s[i2])
            return false; // definitely not sorted
    }
    return true; // probably sorted
}
share
8  
If you set the number of iterations to -n^2*ln(1-p), you can ensure with a probability of p that all combinations will be checked! –  Hannesh Feb 27 at 22:20
    
And what values of p are valid for this solution to be accepted as "working code but trolling"? :) –  fejesjoco Feb 28 at 9:16
2  
From stackoverflow.com/questions/2580933, the chance of miscalculation of a comparison due to cosmic rays would be 0.0000018 (1.8e-6) every second. So if: 1) you can figure out how long an iteration takes, 2) We can use @Hannesh 's formula to calculate the probability, and then solve the system of equations to find the number of iterations that make your solution indistinguishable from a standard isSorted method. –  Xantix Mar 3 at 8:03

Python

If the list is sorted, every number is either less than or equal to the next number. Therefore removing the left-most number will bring the average value up, otherwise the list isn't sorted. We will put this in a loop to check each number

def is_sorted(lst):
    def _avg(lst):
        return sum(lst)/(1.0*len(lst))
    for i in range(len(lst)-1):
        if _avg(lst[i:]) > _avg(lst[i+1:]):
            return False
    return True

is_sorted([1,2,3]) #True
is_sorted([3,2,1]) #False
is_sorted([1,4,3,2,0,3,4,5]) #False


The observant reader will notice that it doesn't exactly work like that.
is_sorted([1,4,3,2,0,3,4,11]) #False
is_sorted([1,4,3,2,0,3,4,12]) #True
is_sorted([1,2,1,2,1,2,1,2,99]) #True

share

Bash

mkdir -p nums
mynums=(1 2 3 4)
for i in "${mynums[@]}"
do
     touch "nums/$i"
done

result=`ls -v nums`
resultarray=(${result})
for i in "${!resultarray[@]}"
do
    if [ ${resultarray[$i]} != ${mynums[$i]} ]; then
        echo "not sorted!"
        rm -rf nums/*
        exit 1
    fi
done
echo "sorted!"
rm -rf nums/*

touch a file for each element in the array, ls the directory and compare the ls result to the original array.

I am not very good with bash, I just wanted to give it a try :)

share
    
Nice one, this assumes that the directory "./nums" already exists though. Maybe a "mkdir -p nums" somewhere? –  camelthemammel Feb 28 at 9:48
    
Oh, yeah that makes sense :P –  SirBraneDamuj Feb 28 at 13:13

C#

The notions of "smaller" or "bigger" are so much 2013. Real programmers only use the modulo operator!

private static void Main()
{
    List<int> list = new List<int> { 1, 5, 7, 15, 22};
    List<int> list2 = new List<int> { 1, 5, 15, 7, 22 };

    bool a = IsSorted(list); // true
    bool b = IsSorted(list2); // false
}

private static bool IsSorted(List<int> list)
{
    for(int i = 0; i % list.Count != list.Count() - 1; i++)
    {
        if (list[i] % list[i + 1] != list[i] &&
            list[i] != list[i + 1])
        {
            return false;
        }
    }
    return true;
}
share
    
What if the same number appears twice? Then list[i] % list[i+1] == 0. –  Simon Feb 27 at 19:57
    
@Simon Oh ho! Indeed, I guess two identical numbers are sorted. Added a comparison for this edge case. Nice find. –  Pierre-Luc Pineault Feb 27 at 20:14
5  
Glad to know that {0, -1, 2} is a sorted list. –  Pierre Arlaud Feb 28 at 14:16
9  
@ArlaudPierre If you want to be a real 2014 programmer, you have to put aside everything that is negative. The world is positive, the world is absolute, the world is modulo! –  Pierre-Luc Pineault Feb 28 at 15:28
1  
Since you don't like the notion of "bigger" and "smaller", it's a shame you had to include those less-than and greater-than signs. You should have used arrays rather than lists. –  Mr Lister Mar 1 at 13:44

Scala

Checking if an array is sorted is easy! Just check if the first element is less than the second. Then sort the rest and see if they're equal.

Unfortunately, sorting is a difficult problem. There aren't many well-known or efficient algorithms for sorting an array; in fact it's a huge blind-spot in the current state of computer science knowledge. So I propose a simple algorithm: shuffle the array and then check if it's sorted, which, as already stated, is easy! Keep shuffling until it's sorted.

object Random {
  def isSorted(list: List[Int]): Boolean = {
    if (list.size <= 1) {
      true
    } else {
      sort(list.tail) == list.tail && list.head <= list.tail.head
    }
  }

  def sort(list: List[Int]): List[Int] = {
    val rand = new scala.util.Random()
    var attempt = list
    do {
      attempt = rand.shuffle(attempt)
    } while (!isSorted(attempt))
    attempt
  }

  def main(args: Array[String]): Unit = {
    println(isSorted(List(1, 2, 3)))
    println(isSorted(List(1, 3, 2)))
    println(isSorted(List(1, 2, 3, 4, 5, 6, 7, 8)))
  }
}

I assume this outputs "true, false, true". It's been running for a while now...

share

A sorted array of integers has the property that every sub-array (say elements n through m of the array) is also a sorted array of integers. This obviously implies that the best method is a RECURSIVE function:

bool isSorted_inner(const std::vector<int> &array, int start, int length){
    if (length == 2){
        if (array[start] < array[start+1]){
            return true;
        }else{
            return false;
        }
    }else{
        return isSorted_inner(array, start, length-1) && isSorted_inner(array, start+1, length-1);
    }
}

bool isSorted(const std::vector<int> &array){
    return isSorted_inner(array, 0, array.size());
}

It may not be the fastest method but it is none-the-less a VERY ACCURATE test of whether or not a list is ordered. It is also incredibly easy to read and understand this code because it uses a FUNCTIONAL paradigm, and is therefore free of the horrors of state changing and iterative loops.

I hope this will be useful information for you.

share

C# - longest increasing subsequence

For a sorted array, the length of the longest increasing subsequence is equal to the length of the array. I copied the algorithm from here, only modified it to be non-decreasing instead of increasing.

static bool isSorted(int[] s)
{
    return s.Length == LongestIncreasingSeq(s);
}

static public int LongestIncreasingSeq(int[] s)
{
    int[] l = new int[s.Length];  // DP table for max length[i]
    int[] p = new int[s.Length];  // DP table for predeccesor[i]
    int max = int.MinValue;

    l[0] = 1;

    for (int i = 0; i < s.Length; i++)
        p[i] = -1;

    for (int i = 1; i < s.Length; i++)
    {
        l[i] = 1;
        for (int j = 0; j < i; j++)
        {
            if (s[j] <= s[i] && l[j] + 1 > l[i])
            {
                l[i] = l[j] + 1;
                p[i] = j;
                if (l[i] > max)
                    max = l[i];
            }
        }
    }
    return max;
}
share

Stonescript (c) LMSingh - 0 minus (4102 palindromed).

Following is written in Stonescript(c), a language copyrighted and used by me many centuries ago, i.e. in olden times before the midgetframes. NOTE: It is a precursor to Sanskrit.

1. Find a very straight stick in the jungle.  
2. Sum up all the values of the array elements and find that many equal sized stones.  
3. Line up all the values of the array along the side of straight stick from step 1. Each value is to be represented by number of stones for each array element like so...  

Example of an array with 8 elements. Sorted in descending order :-)

o
oo
oo
oooo
ooooo
ooooo
ooooo
oooooo
ooooooo
oooooooo
========
12345678

-- Code continued.

4. E-ball-uate. (In Shakespearean English that means Eye ball it.)  
  4.1 Run your eye from array position 1 top towards array position 8 top.  
  4.2 If it looks sorted, then it is.  
  4.2.1 Start jumping up and down and thumping chest.  
  4.2.2 Go to happy end.  
  4.3 If something isn't quite right, like in case of example below then it isn't.  
  4.3.1 Kick the stones in frustration and anger! Cuz it really is not sorted!  
  4.3.2 Go to sad end.  

Example of an array with 8 elements. Not sorted :-(

o
oo
oo
oo o
ooooo
ooooo
ooooo
oooooo
ooooooo
oooooooo
========
12345678

-- Code continued.

5. Sad end.  
  5.1 Eat an apple.  
  5.2 Fall from grace to next line.  
6. Happy end.  

=-=-=-=-=-=
On further optimization, step 4 punch leaves can be replaced with the following punch leaves.
=-=-=-=-=-=

4. Roll a stone from top of position 1 towards top of position 8, pushing the rolling stone towards the top stone for each position while moving to the right.  
  4.1 If rolling stone reaches the position 8 then it's sorted.  
  4.1.1 Start jumping up and down and thumping chest.  
  4.1.2 Go to happy end.  
  4.2 If the rolling stone gets stuck in a trough, then it isn't.  
  4.3.1 Kick the stones in frustration and anger!  
  4.3.2 Go to sad end.  

=-=-=-=-=-=
For you all code sleuths and power debuggers out there, I've intentionally added a bug in the above second variation of step 4. Can you find it?

share
3  
I found the bug - all 4.3.* should be 4.2.* –  Timtech Mar 3 at 18:26

Javascript

This is what made you shocked about the "creativity":

  • Because for a sorted array

    * all the elements on the left side of any element must be smaller 
    * all the elements on the right side of any element must be bigger
    
  • Therefore, run a main loop for all elements and check the above two conditions by running two nested loops inside the main one (one for left side and one for right side)

So, i give a javascript implementation of the described algorithm:

function checkArraySorted(array) {
  for (a = 0; a < array.length; a++) {
    for (b = 0; b < a; b++) {
       if (array[b] > array[a]) return false;
    }
    for (b = a + 1; b < array.length; b++) {
       if (array[b] < array[a]) return false;
    }
  }
  return true;
}

Lets test it:

checkArraySorted([]);
> true

checkArraySorted([1]);
> true

checkArraySorted([1, 2]);
> true

checkArraySorted([2, 1]);
> false

checkArraySorted([1, 2, 3]);
> true

checkArraySorted([1, 2, 3, 4]);
> true

Seems to work perfectly! It has a complexity of O(n²), ideal for an algorithm that should be O(n), but by doing O(n²) it becomes more efficient, since this is a measure of efficiency, so O(n²) is more efficient than O(n).

share
    
I didn't mean to use a 'mid'. The first nested loop was from 0 to a, and the second was supposed to be from a+1 to length. BTW, 1,2,3 should be sorted, isn't it? –  microbian Feb 27 at 18:50
    
@microbian Ok, edited. –  Victor Feb 27 at 18:57
    
+1'ed. Exactly what the candidate wrote. –  microbian Feb 27 at 19:00

C

Hereafter, "sorted" means "sorted in ascending order".

An array is not sorted iff a[i]>a[i+1]

So if we let x=a[i]-a[i+1], x will be positive iff the array is not sorted.

To test for x being positive, we can break it down into two parts: x is not negative, and x is not zero

A simple test for whether x is negative is that we test whether x*x is equal to x*abs(x). This condition should be false if x is negative, since (-1)*(-1)==1.

To test for zero, we can use another simple test: 0./(float)x is Not a Number iff x is zero.

So here's the entire code: (assumes the array has 5 elements)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
    int i, a[5];
    for(i=0;i<5;i++) scanf("%d",&a[i]);
    int sorted=1;
    for(i=0;i<4;i++) {
        int x=a[i]-a[i+1];
        if(x*x==x*abs(x)&&!isnan(0./(float)x)) {
            sorted=0;
            break;
        }
    }
    puts(sorted?"sorted":"not sorted");
    return 0;
}
share
    
Actually, testing for a[i]-a[i+1] > 0 is already problematic. Don't need to do all those kinds of stuffs. –  n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Feb 28 at 9:15
    
Doing unnecessary stuff is the whole point of code trolling, isn't it? (And what do you mean by problematic?) –  ace Feb 28 at 11:01
1  
Signed integer overflow is UB. Even if we define wrap around behavior, if we do INT_MAX - INT_MIN then the result will be a negative number (replace a[i] with INT_MAX and a[i+1] with INT_MIN). –  n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Feb 28 at 14:29
    
Since it is only a homework problem, let's assume that the teacher won't give so many extreme numbers. –  ace Feb 28 at 14:42
    
OK. Just that I prefer to troll + being evil. –  n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Feb 28 at 14:44

It is all about how certain you wish to be. Since no certainty was given the following is actually quite good performance wise. The code below gives a good guess, but if you are sure you should repeat the function a couple of times. If you wish to be really sure, you should run it in a loop and do it a dozen of times. Perfect scalability!

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

static const int size = 100;

int issorted(int *array, int size)
{
    int idx = random() % size;
    return (array[idx] >= array[0]);
}

void check_array(int *array, int size)
{
    if (issorted(array, size)) {
        puts("The array is sorted but I am not 100% sure.");
    } else {
        puts("The array is definitely not sorted in ascending order.");
    }
}

int main(void)
{
    int *array = malloc(sizeof(int) * size);
    int i = 0;

    srand(time(NULL));

    for (i = 0; i < size; i++) {
        array[i] = random();
    }

    check_array(array, size);

    for (i = 0; i < size; i++) {
        array[i] = i + 1;
    }

    check_array(array, size);
    free(array);

    return 0;
}

Isn't this a treat?

share

C

int is_sorted(int *T, int n)
{
return false;
}

Works with probability 1-(1/n!) and complexity O(1). Obviously the best method for very large random arrays.

As the complexity is only O(1), for a better estimation, run twice.

share

C

This function does more than just tell you if the array is sorted. It tells you how many elements are in the right place. It can be used for any type of data.

Note the importance of using descriptive variable names to make your code easy to follow. On the other hand, we do not need to declare the variable i, as it is bound to be declared somewhere else in the program.

int sortcheck(array_to_be_checked[10])
{
  int number_of_elements_in_right_place=0;

  for (i = 1; i = 10; i++)
    number_of_elements_in_right_place += i == array_to_be_checked[i];

  return number_of_elements_in_right_place;
}

Edit: This is a better way for larger arrays. The advantage of this is that it is similar to the way a human would check.

int sortcheck(array_to_be_checked[32767])
{
  i=rand(); j=rand();
  while( (array_to_be_checked[i] > array_to_be_checked[j]) = (i > j) ) 
  {
    printf("I think it's sorted");
    i=rand(); j=rand();
  };
  printf("It wasn't sorted");
}
share
1  
"We do not need to declare the variable i, as it is bound to be declared somewhere else in the program." was worth a laugh. –  Jonathan Van Matre Feb 27 at 22:53
    
@JonathanVanMatre Thanks but it's by no means the only thing wrong with this code. –  steveverrill Feb 27 at 22:55

JavaScript + more statistics

I liked the solution suggested by @Cominterm a lot. But comparing to an already sorted list? That's cheating!

Instead, I calculate the array's autocorrelation (correlation between the array and the array left shifted one position). Then, I shuffle the array lots of times and each time compare it's new autocorrelation to the original autocorrelation. If the array was sorted, the original autocorrelation would be the highest most of the time!

http://jsfiddle.net/dB8HB/

Bonus: If your p-value < 0.05, the output will automate the task of claiming that the array is sorted for you. What more could you ask for?

Bonus2: Although this implementation uses JavaScript's O(n) array functions for convenience, the approach could use sampling to run in constant time!

<form name="out"><textarea name="put" cols="80" rows="3">Press the button</textarea></form> 
<button onclick="startstop();">The button</button>
<script>
var iid=input=0, my=document.forms, isit={'true':0.5,'false':0.5}, ownAutocorr;
function startstop(){
     if(iid){
        clearInterval(iid);
        if(1 - isit.true / (isit.true+isit.false)<0.05){my.out.put.value+="\nYour array is sorted! (p<0.05)";}
        iid=input=0;isit={'true':0.5,'false':0.5}
     }
     else   {
        input=JSON.parse("["+prompt("Comma separated integers")+"]");
        ownAutocorr=pearsonCorrelation(input,cloneShiftArray(input));
        iid=setInterval(trial,50);
    }
}

function trial(){

 var newArr=shuffle(input.slice(0));
 var newAutocorr=pearsonCorrelation(newArr,cloneShiftArray(newArr));
 isit[newAutocorr<ownAutocorr]++;
 my.out.put.value="Your array is sorted with probability " + (isit.true / (isit.true+isit.false)).toFixed(2);
}

function cloneShiftArray(oldArr){
    var newArr=oldArr.slice(0); //clone the array
    var len=oldArr.length;
    //shift the array one
    for(var l=0;l<len-1;l++){
     //performance is important so we'll use bitwise operators
     newArr[l]^=newArr[l+1];
     newArr[l+1]^=newArr[l];
     newArr[l]^=newArr[l+1];
    }
    newArr[l]+=newArr[l-1   ];
    return newArr;
}
function pearsonCorrelation(p1, p2) { //Borrowed from teh interwebs
  var len = p1.length;
  var sum1=sum2=sum1Sq=sum2Sq=pSum = 0;
  for (var l = 0; l < len; l++) sum1 += p1[l];
  for (var l = 0; l < len; l++) sum2 += p2[l];
  for (var l = 0; l < len; l++) sum1Sq += Math.pow(p1[l], 2);
  for (var l = 0; l < len; l++) sum2Sq += Math.pow(p2[l], 2);
  for (var l = 0; l < len; l++) pSum += p1[l] * p2[l];
  var num = pSum - (sum1 * sum2 / len);
  var den = Math.sqrt((sum1Sq - Math.pow(sum1, 2) / len) *
      (sum2Sq - Math.pow(sum2, 2) / len));
  if (den == 0) return 0;
  return num / den;
}
function shuffle(array) {//also borrowed
  var currentIndex = array.length, temporaryValue, randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
}
</script>
share

JavaScript/SVG - sunDialsort

This solution does not use the <,<=,> or >= comparators. I've attempted to make it read as little like a sort function as possible.

Method

  • Plot the values as dots along an arc.
  • For an ascending array each value will make the total width of the drawing wider and not decrease the starting X (exception: two identical values).
  • As width can't shrink a != will suffice,
  • As X cannot increase an == will suffice.
  • to fix for two identical values each dot is actually a line, of increasing length. Where the unit length is less than 1/number of values.

Trolling

I've added the following face-palms along the journey of reading this very bad code.

  • function may look like its going to sort the array, named it sunDialsort (bonus bad capitalization)
  • used lit-geek reference for all variable names
  • used the regex hammer to count the number of elements in the array
  • used an alert box
  • the solution for the edge case where 2 consecutive variables are the same doubled the amount of code (a one liner could have sorted it), put lots of this code early to confuse the purpose of the function.
  • instead of finding the min and max find the longest number and round up to the next power of ten, hopefully this will throw people off the scent.

xml

<body>
<svg id="dial" height="400" width="400" transform=""></svg>
</body>

function

sunDialsort = function (values)
{
    var twas = values.toString();  
    var brillig = twas.match(/,/g).length + 1; //<1>
    //find the sig figs we are working with (longest number)
    var and = [], the = 0;
    for (var jabberwock = 0; jabberwock < twas.length; jabberwock++)
    {
        switch (twas.charAt(jabberwock))
        {
        case ("."):
            break; //dont count
        case (","):
            and.push(the);
            the = 0;
            break;
        default:
            the++;
        }
    }
    and.push(the);
    var slithy = Math.max.apply(Math, and);
    //assume did/toves based on number of characters
    var toves = Math.pow(10, slithy);
    var did = toves * -1;
    console.log(did + "," + toves + "," + brillig);
    //for each number make a horizontal svg line of length (jabberwock*acuuracy)     
    var gyre = 1 / brillig;
    var gimble, wabe, all, mimsy, were, borogoves, mome, raths;
    var outgrabe = true;
    for (jabberwock = 0; jabberwock < brillig; jabberwock++)
    {
        gimble = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        gimble.setAttribute("stroke", "blue"); //green is not a creative colour
        gimble.setAttribute("d", "M0 20 h " + (jabberwock * gyre));
        wabe = (values[jabberwock] - did) / (toves - did);
        mimsy = 90 - (wabe * 180);
        gimble.setAttribute("transform", "rotate(" + mimsy + ")");
        document.getElementById("dial").appendChild(gimble);
        borogoves = document.getElementById("dial").getBBox();
        if (mome)
        {
            raths = (borogoves.width != all && were == borogoves.x);
            console.log("test " + raths);
            all = borogoves.width;
            if (!raths)
            {
                outgrabe = false
            }
        }
        else
        {
            were = borogoves.x;
            all = borogoves.width;
            mome = true;
        }
    }
    return outgrabe
};
alert(sunDialsort([1, 2, 3, 3, 4341, 556]));

If anyone wants to test there is a version here with readable variable names. http://jsfiddle.net/outRideACrisis/r8Awy/

share

C

As a binary search only works on sorted arrays, to check if an array is sorted, all we need to do is verify that a binary search works for all elements of the array. If it fails to find any element, we know the array is not sorted.

The command-line arguments passed must all be decimal integers without leading zeroes.

#include <stdlib.h>
#include <string.h>

int compar(const void *a, const void *b) {
  char *const *sa = a, *const *sb = b;
  int cmp = strlen(*sa) - strlen(*sb);
  if (cmp == 0) cmp = strcmp(*sa, *sb);
  if (cmp == 0) cmp = sa - sb;
  return cmp;
}

int main(int argc, char *argv[]) {
  if (argc-- && argv++) {
    for (int i = 0; i != argc; i++) {
      if (bsearch(argv+i, argv, argc, sizeof *argv, compar) != argv+i) {
        return 1;
      }
    }
  }
  return 0;
}
share

Javascript

a = prompt("Please enter the data");
r = prompt("Does your array arouse moral distaste and contempt?");
if ((/yes/i).test(r))
  alert("The array is sordid.");
share
1  
{69, 313, 187, 31338} –  Geobits Mar 5 at 14:33

C

  • Make a copy of the array
  • sort the copy in descending order
  • check if this array is the reverse of the given array
    #include<stdio.h>
    #include<stdlib.h>
    #include <stddef.h>
    #include<string.h>
    int main(){
     int arr[100],i,j,temp;
     int a[] = {1,2,3,4,5,6,7,8,9,10};
     char b[256];

     printf("Loading the program please wait...");
      int s = sizeof(a)/sizeof(a[0]);
     for(i=0; i<999999999; i++);//best way to make the program more realistic
     system("cls");

     for(i=0;i<s; i++ )
     arr[i] = a[i];

     for(i=0;i<s;i++){
          for(j=i;j<s;j++){
               if(arr[i] < arr[j]){
               temp=arr[i];
               arr[i]=arr[j];
               arr[j]=temp;
               }
           }
     } //sorting array in descending order

     int p = 0;
     for(i=0; i<s; i++)
     {
         if (a[s-i-1] != arr[i])
         p++;
     }

     if(p>0)
     printf("No");
     else
     printf("yes");
     getch();


     }
share

Mathematica

This algorithm seems to work, but it is a bit slow. There may be quicker ways to sort but I haven't found them.

  1. Take a random ordering of the list and check whether it is in order (with OrderedQ).
  2. If it is, stop. Otherwise, repeat step 1.

The following code sorted the list in just over 18 seconds.

a = {23, 50, 16, 57, 19, 60, 40, 7, 30, 54};
n = 1;
Timing[While[! OrderedQ[a], a = RandomSample[a]; n++]]
n
a

{18.581763, Null}
8980699
{7, 16, 19, 23, 30, 40, 50, 54, 57, 60}

share
    
The task was to check if the input is already sorted. –  Ilmari Karonen Feb 28 at 18:41
    
This is the essential idea behind my solution (though, I use a quadratic-time OrderedQ just for funsies) with the added check at the end "now that we've got a sorted one, is it what we started with?" –  boothby Feb 28 at 18:45

JavaScript

function isSorted(arr) {
    if (arr.length === 1 && typeof arr[0] !== 'number' || arr[0].toString().indexOf('.') !== -1 || arr[0] > (-1 >>> 0) || arr[0] !== arr[0] || arr[0] === Infinity) {
        // Return false in the case of one non-number element.
        // isSorted returns false for arrays containing non-numbers for consistency
        // with PHP, but that doesn’t work for one element, so that’s the purpose
        // of this check.
        return false;
    }

    var obj = {};
    var i;

    for (i = arr.length; i--;)
        obj[arr[i]] = true;

    for (var x in obj)
        if (arr[++i] != x) return false;

    return true;
}

This function may return false incorrectly, but not on modern browsers; you can check for this and provide a slower fallback (as described in the question) if necessary:

var isModern = /chrome/i.test(typeof navigator === 'object' && navigator.userAgent);

if (!isModern) {
    isSorted = function() {
        // I develop on good browsers, so the implementation is left as an exercise
        // to the reader if he or she wants to support outdated browsers.
    };
}

They say this gives unpredictable results on negative numbers, but what it’s really all up to is how good you are at predicting things.

share
2  
I wish Chrome would shuffle object properties to prevent people from doing things like this… –  Bergi Mar 2 at 13:29

Java (Levenshtein Distance)

In this implementation, I clone the original array and sort the cloned instance. Then, the Levenshtein distance is calculated. If it is zero, then the original array was sorted.

Note: The getLevenshteinDistance() implementation is taken from Jakarta Commons Lang and modified to work on int[] instead of CharSequence.

import java.util.Arrays;

public class CheckSorting {

    public boolean isSorted(int[] array) {
        int[] sortedArray = Arrays.copyOf(array, array.length);
        Arrays.sort(sortedArray);

        return CheckSorting.getLevenshteinDistance(array, sortedArray) == 0;
    }

    public static int getLevenshteinDistance(int[] s, int[] t) {
        int n = s.length;
        int m = t.length;

        if (n == 0) {
            return m;
        } else if (m == 0) {
            return n;
        }

        if (n > m) {
            int[] tmp = s;
            s = t;
            t = tmp;
            n = m;
            m = t.length;
        }

        int p[] = new int[n + 1];
        int d[] = new int[n + 1];
        int _d[];

        int i;
        int j;

        int t_j;

        int cost;

        for (i = 0; i <= n; i++) {
            p[i] = i;
        }

        for (j = 1; j <= m; j++) {
            t_j = t[j - 1];
            d[0] = j;

            for (i = 1; i <= n; i++) {
                cost = s[i - 1] == t_j ? 0 : 1;
                d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
            }

            _d = p;
            p = d;
            d = _d;
        }
        return p[n];
    }
}
share

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