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.