Partition adjustment of the [algorithm] array

Source: Internet
Author: User

Topic One:

Given an ordered array of arr, adjust arr so that the left half of the array does not have a repeating part and ascending, without guaranteeing that the right part is ordered.

For example: arr=[1,2,2,2,3,3,4,5,6,6,7,7,8,8,9,9], adjusted after arr=[1,2,3,4,5,6,7,8,9 ...].

Requirements:

Time complexity O (N), additional space complexity O (1)

Program:
 Public Static void leftunique (int[] arr) {
if Null | | Arr.length < 2) {
return;
}
int u = 0;
int i = 1;
 while (I! = arr.length) {
if (arr[i++]! = Arr[u]) {
Swap (arr, ++u, i-1);
}
}
}
Topic Two:

Given an array of arr, which may contain only 0, 1, and 23 values, implement the sort of arr.

Another way to ask: There is an array, where only the red ball, basketball and yellow ball, please implement the red ball all placed on the left side of the array, basketball in the middle, yellow ball on the right.

Another way to ask: There is an array, and then given a value k, to achieve a number smaller than k is placed on the left side of the array, equal to the value of K is placed in the middle of the array, larger than the number of K is placed on the right side of the array.

Program:
 Public Static void sort (int[] arr) {
if Null | | Arr.length < 2) {
return;
}
int left =-1;
int index = 0;
int right = Arr.length;
 while (Index < right) {
if (Arr[index] = = 0) {
Swap (arr, ++left, index++);
Else if (Arr[index] = = 2) {
Swap (arr, index,--right);
Else {
index++;
}
}
}

Partition adjustment of the [algorithm] array

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.