📜  3向QuickSort(荷兰国旗)(1)

📅  最后修改于: 2023-12-03 14:38:52.252000             🧑  作者: Mango

QuickSort with 3-Way Partitioning (Dutch National Flag)

QuickSort is a popular sorting algorithm, commonly used for large datasets. It follows a divide-and-conquer strategy and has an average time complexity of O(n*logn). However, traditional QuickSort with a 2-way partition has limitations when it comes to sorting arrays with many duplicates. This is where the 3-way partitioning (Dutch National Flag) variant comes in.

What is Dutch National Flag Problem?

Dutch National Flag problem is a problem of arranging an array containing only 3 distinct elements in O(n) time complexity.

How Does 3-Way Partitioning Work?

In traditional QuickSort, we choose a pivot element, partition the array into two sub-arrays: the left sub-array containing elements smaller than the pivot, and the right sub-array containing elements greater than the pivot. We recursively apply the same process to the left and right sub-arrays until the array is sorted.

In QuickSort with 3-way partitioning, we add a third sub-array that contains elements equal to the pivot. Instead of splitting the array into two sub-arrays, we split it into three sub-arrays: the left sub-array contains elements smaller than the pivot, the middle sub-array contains elements equal to the pivot, and the right sub-array contains elements greater than the pivot. We recursively apply the same process to the left and right sub-arrays until the array is sorted.

void QuickSort(int[] arr, int low, int high) {
   if(low<high) {
      int pi[] = partition(arr, low, high);
      QuickSort(arr, low, pi[0]-1);
      QuickSort(arr, pi[1]+1, high);
   }
}

int[] partition(int[] arr, int low, int high) {
   int pivot = arr[low];
   int i = low+1;
   int lt = low;
   int gt = high;

   while(i<=gt) {
      if(arr[i]<pivot) {
         swap(arr, i, lt);
         i++;
         lt++;
      } else if(arr[i]>pivot) {
         swap(arr, i, gt);
         gt--;
      } else {
         i++;
      }
   }
   return new int[] {lt, gt};
}

void swap(int[] arr, int i, int j) {
   int temp = arr[i];
   arr[i] = arr[j];
   arr[j] = temp;
}
Benefits of using 3-Way Partitioning
  • Helps in optimizing the performance of QuickSort in case of arrays with repeating elements by reducing the number of comparisons needed.
  • Reduces the amount of redundant computation during the partitioning process by cutting down on duplicate values.
  • It reduces the number of recursive calls needed by eliminating the need to partition arrays that already have been partitioned.
Conclusion

QuickSort with 3-way partitioning provides a better solution to sorting arrays with many duplicates. It's an efficient and straightforward algorithm that's easy to implement. If you're working with large datasets with lots of repeating elements, you should consider using the 3-way partitioning technique to optimize your QuickSort algorithm.