荷蘭國旗排序圖示
荷蘭國旗排序code
int arr[] = {9, 8, 5, 7, 4, 9, 7, 5, 9, 8, 4, 2, 6, 5, 9, 1, 7, 5, 9,88,11};
@Test
public void quickSortTest(){
quickSort(arr,0,arr.length-1);
printArr();
}
public void quickSort(int[] arr, int l, int r) {
if (l < r) {
int[] p = partition(arr, l, r);
quickSort(arr, l, p[0] - 1);
quickSort(arr, p[1] + 1, r);
}
}
private int[] partition(int[] arr, int l, int r) {
int less = l - 1;
int more = r ;
while (l < more) {
if (arr[l] < arr[r]) {//左邊
swap(++less, l++);
} else if (arr[l] > arr[r]) {
swap(--more, l);
} else {
l++;
}
}
swap(more,r);
int[] ints = {less + 1, more};//return index
return ints;
}
[圖片上傳失敗...(image-cf73bb-1563555823413)]
@Test
public void test8() {
String str = "aaafvjvnrjoooobbggggcc";
boolean tag = false;
char[] chars = str.toCharArray();
StringBuilder sb = new StringBuilder();
int len = chars.length - 1;
for (int i = 0; i < len; i++) {
if (i + 1 <= len && chars[i] == chars[i + 1]) {
if (!tag) {
sb.append(chars[i]).append(chars[i + 1]);
tag = true;
} else {
sb.append(chars[i]);
}
} else {
if (tag && i < len - 1) {
sb.append(",");
}
tag = false;
}
}
System.out.println("sb:--> " + sb.toString());
}