Given an integer N, the task is to find N elements which fail the below-sorting algorithm. If none of the N elements fail, then print -1.
loop i from 1 to n-1 loop j from i to n-1 if a[j]>a[i+1] swap(a[i], a[j+1])
Input: N = 10 Output: 10 9 8 7 6 5 4 3 2 1 Input: N = 2 Output: -1
Approach: On solving for various cases, we can observe that only for n<=2, the given algorithm is invalid. Any value of N above that will fail on the given algorithm. A sorted array consisiting of N numbers(1, 2, 3 . . N) in reverse order cannot be sorted using this given algorithm.
Below is the implementation of the above approach:
3 2 1
Time Complexity: O(N)
Auxiliary Space: O(1)
- Know Your Sorting Algorithm | Set 1 (Sorting Weapons used by Programming Languages)
- Sorting objects using In-Place sorting algorithm
- Know Your Sorting Algorithm | Set 2 (Introsort- C++’s Sorting Weapon)
- Case-specific Sorting of Strings
- Case-specific sorting of Strings in O(n) time and O(1) space
- Sorting Algorithm Visualization : Merge Sort
- Bead Sort | A Natural Sorting Algorithm
- A sorting algorithm that slightly improves on selection sort
- Which sorting algorithm makes minimum number of memory writes?
- Algorithm Library | C++ Magicians STL Algorithm
- When does the worst case of Quicksort occur?
- How to make Mergesort to perform O(n) comparisons in best case?
- Test Case Generation | Set 3 (Unweighted and Weighted Trees)
- Find a permutation that causes worst case of Merge Sort
- Test Case Generation | Set 1 (Random Numbers, Arrays and Matrices)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.