Created
July 23, 2015 22:17
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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