I need to write an algorithm of sorting the array of size [0..N-1], that is filled with the values of the range [0..N-1]. Values in the array can not be repeated. The sorting should work in a linear time, and I allowed to use only some additional variable.
plz comment the code i wrote. As far as I guess the worst time is 2*N. Is is still a linear time? Is it possible to make is faster?
public int sort(){
int i = 0;
while (i < n){
if (a[i] != i)
switchElements(a[i], a[a[i]]);
else
i++;
}
return count;
}
additional 1
I really need to sort the array, cause sorting is only the part of the task. The full task is to find is there a duplicate values in array, in a linear time, and no additional variables.
In order to detect duplicates you can extend that logic further, forcing the values into their respective spots.
and in the end, if for any
i,iandA[i]do not match that would indicate a repetition!Overall it would be still
O(N)procedure.For more details refer to following post:
Finding duplicates in O(n) time and O(1) space