Hard Algorithms

Sort a list

The first INPUT () is how many numbers follow. Read them into a list, sort the list from smallest to largest by swapping elements, and DISPLAY the list.

Hint: compare neighbors and swap them when they are out of order; repeat until no swap happens.

Input (one value per INPUT ())Expected output
5 5 2 9 1 7[1, 2, 5, 7, 9]
3 1 2 3[1, 2, 3]

Check runs all 3 tests. Press Run to try the program yourself: a box asks for each INPUT ().

Output


        
        
      

Variables

Show a solution
count ← INPUT ()
nums ← []
REPEAT count TIMES
{
   APPEND (nums, INPUT ())
}
swapped ← true
REPEAT UNTIL (NOT swapped)
{
   swapped ← false
   i ← 1
   REPEAT UNTIL (i ≥ LENGTH (nums))
   {
      IF (nums[i] > nums[i + 1])
      {
         temp ← nums[i]
         nums[i] ← nums[i + 1]
         nums[i + 1] ← temp
         swapped ← true
      }
      i ← i + 1
   }
}
DISPLAY (nums)

Teachers: sign in as a teacher to add this exercise to a class, graded automatically.

Frequently asked questions

How do I solve this exercise?

Complete the starter code in the editor, press Run to try it (type values when INPUT () asks), then press Check to run every test. Step shows the program line by line with its variables.

Where is the solution?

Under the editor, in Show a solution. Try the exercise first: comparing your code with the solution afterwards is a good way to learn another approach.

AP is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this site.