荷兰国旗问题

荷兰国旗:

给定一个数组arr和一个数num,将其分为三个区域:左侧为<num的区域,中间为=num的区域,右侧为等于num的区域

代码及解析:

 1 //给定一个数组arr和一个数num,把小于num的数放在左边,等于num的数放中间,大于num的数放在右边
 2     public static void PartitionByOneNumMore(int[] arr,int num)
 3     {
 4         int curIndex = 0;
 5         int    minIndex = -1, maxIndex = arr.length;//此种写法可以更准确的表示minIndex和maxIndex作为小于区域和
 6                                                  //大于区域的边界
 7         while (curIndex < maxIndex) {
 8             if (arr[curIndex] < num) {//如果小于num,则将当前数和小于区域右边的那个数进行交换,并将小于
 9                                       //区域的范围在右扩一位
10                 swap(arr,curIndex++,++minIndex);
11             }
12             else if (arr[curIndex] == num) {//等于num则什么都不做,将当前位置右移一位
13                 curIndex++;
14             }
15             else {//大于那个数,则将当前位置数与大于区域左侧的数做交换,并将大于区域左扩一位
16                 swap(arr,curIndex,--maxIndex);
17             }
18         }
19     }

 

posted @ 2022-04-05 15:07  jue1e0  阅读(65)  评论(0)    收藏  举报