|
| 1 | +In this problem your goal is to sort an array consisting of n integers in at most n swaps. |
| 2 | +For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. |
| 3 | + |
| 4 | +Note that in this problem you do not have to minimize the number of swaps � your task is to find any sequence that is no longer than n. |
| 5 | + |
| 6 | +-------------------------------- |
| 7 | + |
| 8 | +Didn't expect a O(n^2) solution to pass. Took a long time to write it because I suspected there was a better solution. |
| 9 | + |
| 10 | +Be greedy and perform selection sort. In each iteration place the i-th smallest element at the i-th endex. |
| 11 | + |
| 12 | +Maintain a vector of pairs to keep track of the indices of the swaps. Don't swap if the element is already at the right position. |
| 13 | + |
| 14 | +(Although swapping an element with itself in the same index is allowed in this problem) |
| 15 | + |
| 16 | +In other words, perform selection sort. |
| 17 | + |
| 18 | +------------------------------------- |
| 19 | + |
| 20 | +int main() |
| 21 | +{ |
| 22 | + typedef pair <int, int> pair_int; |
| 23 | + |
| 24 | + int no_of_elements; |
| 25 | + scanf("%d", &no_of_elements); |
| 26 | + |
| 27 | + vector <int> element(no_of_elements); |
| 28 | + |
| 29 | + for(int i = 0; i < no_of_elements; i++) |
| 30 | + scanf("%d", &element[i]); |
| 31 | + |
| 32 | + vector <pair_int> swaps; |
| 33 | + //Selection Sort |
| 34 | + for(int i = 0; i < no_of_elements; i++) |
| 35 | + { |
| 36 | + int min_i_index = i; |
| 37 | + for(int j = i + 1; j < no_of_elements; j++) |
| 38 | + { |
| 39 | + if(element[j] < element[min_i_index]) |
| 40 | + min_i_index = j; |
| 41 | + } |
| 42 | + |
| 43 | + if(min_i_index != i) |
| 44 | + { |
| 45 | + swaps.push_back(make_pair(i, min_i_index)); |
| 46 | + |
| 47 | + swap(element[min_i_index], element[i]); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + printf("%u\n", swaps.size()); |
| 52 | + for(unsigned int i = 0; i < swaps.size(); i++) |
| 53 | + { |
| 54 | + printf("%d %d\n", swaps[i].first, swaps[i].second); |
| 55 | + } |
| 56 | + return 0; |
| 57 | +} |
| 58 | + |
| 59 | + |
0 commit comments