Volumes: Beginner's problems
Array sorting is a popular problem for programming newcomers - and extremely important thing in professional programming (in databases, libraries etc).
Sorting is reordering according to some simple rule based on comparison. Suppose we are given an array:
a = [3, 1, 4, 1, 5, 9, 2, 6]
and we want its elements to be reordered in non-decreasing order - i.e. if one element is placed earlier (to the left) than the other - we can be sure the first element is either less or equal to second.
Mathematically speaking, for any indexes
i < j then
a[i] <= a[j].
Bubble Sort is one of the simplest methods to perform such reordering. We will describe it in even simpler way than usual:
N-1pairs for array of
a[i] <= a[i+1]does not hold, swap these two elements.
It is obvious, that if the pass do not perform any swaps, the array is already sorted and future passes could not change anything.
To swap elements with indexes
j there are few variants. For example temporary variable
t could be used:
t = a[i] a[i] = a[j] a[j] = t
Input data will contain array size in first line and array itself in the second
(integer values separated with spaces).
Answer should contain two values - number of passes perfromed and total number of swaps made. For example:
input data: 8 3 1 4 1 5 9 2 6 answer: 5 8
You are supposed to note that number of swaps is roughly proportional to
N is array size (average is
N^2 / 4) so that time which algorithm takes grows significantly faster than the amount of data (that is why
such sorting is rarely used for bigger arrays).
You may read more in the topic on sorting algorithms comparison