[Algorithm-Java implementation] Divide the array into a form with a small value on the left, equal in the middle, and large on the right.

[Algorithm-Java implementation] Divide the array into a form with a small value on the left, equal in the middle, and large on the right.

1. Problem description:

1. Input: an unordered integer array arr, where the elements in arr are not unique.

Such as: int[] arr = {3, 4, 6, 9, 5, 5, 8, 8, 2, 1, 7, 7, 0 };

2. Output: Divide the array arr according to a certain value into the form of small on the left, equal in the middle, and large on the right , and output.

2. Question answer:

Another way to ask this question:Dutch flag issue

There is an array with only red, blue, and yellow balls. Place the red ball on the left of the array, the blue ball in the middle of the array, and the yellow ball on the right of the array.

Ideas:

1. First use a reference num as the intermediate value, and the cur pointer traverses the array from subscript 0 to subscript arr.length-1.

2. The less pointer initially points to -1, and the more pointer points to arr.length.

3. The cur pointer moves in turn, judges the size relationship between the current cur subscript element and the num value, and performs element exchange.

See the code for specific implementation, and the results are as follows:

Insert picture description here

3. Algorithm analysis:

1. The time complexity is O(N), which is equivalent to traversing an array.

2. The extra space complexity is O(1), no extra space is needed.

code show as below

import java.util.Arrays;
/*
 * 问题:将数组按某值划分成左边小,中间相等,右边大的形式
 * 
 */
public class ArraySort {
    
    
	//测试
	public static void main(String[] args) {
    
    
		int[] arr = {
    
     3, 4, 6, 9, 5, 5, 8, 8, 2, 1, 7, 7, 0 };
		int[] newArr = partition(arr, 0, arr.length - 1, 5);
		System.out.println(Arrays.toString(newArr));
	}
    //算法实现
	public static int[] partition(int[] arr, int L, int R, int num) {
    
    
		int less = -1;
		int more = R + 1;
		int cur = L;
		while (cur < more) {
    
    
			if (arr[cur] > num) {
    
    
				swap(arr, --more, cur);
			} else if (arr[cur] < num) {
    
    
				swap(arr, ++less, cur++);
			} else {
    
    
				cur++;
			}
		}
		return arr;
	}
	//元素交换
	public static void swap(int[] arr, int i, int j) {
    
    
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}
}


Guess you like

Origin blog.csdn.net/hkdhkdhkd/article/details/110823157