Topic:
Given an integer array of length n arr, which has n non-equal natural number 1~n, implement the sort of arr, but do not replace the value on the subscript 0~n-1 position with a direct assignment to 1~n.
Requirements: The time complexity is O (N), the additional space complexity is O (1).
Ideas:
1. Traverse arr from left to right, assuming the current traverse to I position.
2.if arr[i]==i+1, do not need to adjust, continue to traverse.
3.if arr[i]!=i+1, make adjustments.
Depending on how the function is adjusted, different implementations can be implemented.
Method One:
Public Static void sort1 (int[] arr) {
int tmp = 0;
int next = 0;
for (int i = 0; I! = Arr.length; i++) {
TMP = Arr[i];
while (Arr[i]! = i + 1) {
Next = Arr[tmp-1];
ARR[TMP-1] = tmp;
TMP = Next;
}
}
}
Method Two:
Public Static void sort2 (int[] arr) {
int tmp = 0;
for (int i = 0; I! = Arr.length; i++) {
while (Arr[i]! = i + 1) {
TMP = Arr[arr[i]-1];
Arr[arr[i]-1] = arr[i];
Arr[i] = tmp;
}
}
}
[Algorithm] sorting of natural number arrays