Skip to content

Instantly share code, notes, and snippets.

@ravikumar-n
Created July 23, 2015 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravikumar-n/d49f7acd31b46f2c5df5 to your computer and use it in GitHub Desktop.
Save ravikumar-n/d49f7acd31b46f2c5df5 to your computer and use it in GitHub Desktop.
Sort numbers from 1..n in time complexity::o(n) and space complexity o(1).
int []arr = new int[]{2,1,4,1,4};
for(int i=0;i<arr.length; i++) {
if(arr[i] > 0) {
int elementIndex = arr[i] - 1;
if (arr[elementIndex] > 0) {
arr[i] = arr[elementIndex];
arr[elementIndex] = -1;
i--;
} else {
arr[elementIndex]--;
arr[i] = 0;
}
}
}
for(int i=0;i<arr.length;i++) {
System.out.println("Count of "+(i+1) + " is "+Math.abs(arr[i]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment