Given an array, return a sorted array. Further, what if only a pair of consecutive numbers are to be sorted without considering the duplicates? What if instead of a pair, its triplets? Can you form a generic solution? Mention time complexity for each case.
Input: [4, 2, 5, 6, 3, 1, 3, 2, 5]
Output for simple sort: [1, 2, 2, 3, 3, 4, 5, 5, 6]
Output for pair-sorting: [2, 4, 5, 6, 1, 3, 2, 3, 5]
Output for triplet-sorting: [2, 4, 5, 1, 3, 6, 2, 3, 5]
Explanation of simple sort - Its simple sort and align it in line
Explanation of pair-sorting - it picks in pair-wise of 2 elements example from input first pair 4,2 and sort 2,4 and then second pair 5,6 and sort to 5,6, and then 3,1 and sort to 1,3 and so on. Pair wise sorting.
Explanation of triplet-sorting - This pick three elements and sort example from input first 3 elements 4,2,5 and sort to 2,4,5 and so onn...
I want a generic function that takes input of array And type of sort - Example - simple, pair or triplet
and return the result accordingly
int array[] = {4, 2, 5, 6, 3, 1, 3, 2, 5}
for(int i =0; i < array.length; i = i+2) {
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
So far I tried this. But unable to achieve any outcome. Can anyone help me with this? Pseudocode or any language will work. I need to come up with solution.