[Algorithm] sorting of natural number arrays

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.