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)
- Know Your Sorting Algorithm | Set 2 (Introsort- C++’s Sorting Weapon)
- Sorting objects using In-Place sorting algorithm
- Case-specific Sorting of Strings
- Case-specific sorting of Strings in O(n) time and O(1) space
- Bead Sort | A Natural Sorting Algorithm
- Sorting Algorithm Visualization : Merge Sort
- 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
- Can QuickSort be implemented in O(nLogn) worst case time complexity?