-6

A question has arisen on an old exam paper used for revision which asks about a type of sorting that I cannot find the name of anywhere. Hopefully somebody here can help, please?

b. Produce an algorithm which will sort an array so that the largest items are on the ends and the smallest in the middle. For example: [2,6,5,9,12] might become [12,6,2,5,9]

Ron
  • 14,674
  • 4
  • 34
  • 47
Zeusn
  • 1
  • 5
  • Similar to: https://stackoverflow.com/questions/29852044/sorting-list-from-smallest-largest-smallest-in-java you want to check the value against the mean – Giel Aug 13 '17 at 20:34
  • I don't know the name, but an implementation I came up with is a alternating between inserting at the beginning and end into a `std::deque` after standard sorting – Post Self Aug 13 '17 at 20:36
  • Also seems more appropriate on http://cstheory.stackexchange.com – Post Self Aug 13 '17 at 20:42
  • 2
    This question is just mean. I mean it. – user4581301 Aug 13 '17 at 20:43
  • @user4581301 Indeed, I would have found the two largest put them at [0, k] and the two smallest and put them at [ k/2, k/2 + 1]. There is no "sorting" here. – Captain Giraffe Aug 13 '17 at 21:24

2 Answers2

2

Make one pass through the sequence to find the largest value, the second largest value, and the smallest value. Swap the largest to one end, the second largest to the other end, and the smallest to the middle. Voila: largest items are on the ends and the smallest is in the middle. Calling this a "sort" is silly.

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

I guess the point is to create the algo yourself:

Just an idea:

    biggest = value of first element
    smallest= value of first element

    For all elements of the array do:
          If value of current element > biggest
                    biggest = value of current element
                    Add biggest as last element of the array
          If value of current element < smallest
                    smallest =  value of current element

    End of for loop

    Move last element of the the array at first position

    #now the biggest is the first element, the second bigger number is the last one

    Put smallest at middle position of the array [idx max / 2 rounded up]
   # now the smallest is in the middle

I hope it helps. Thomas

Totoc1001
  • 338
  • 2
  • 11
  • Thanks Thomas. Would I be best achieving this using std::deque? – Zeusn Aug 13 '17 at 20:54
  • It might probably help, (http://en.cppreference.com/w/cpp/container/deque) but it's code implementation then, no more algo right? – Totoc1001 Aug 13 '17 at 20:59