На головну

# An Implementation

A quicksort implementation appears in Listing 1. This quicksort implementation uses a basic pivot selection strategy of selecting the middle element. This is a simple approach to implement, but one that can lead to efficiency problems when the algorithm selects either the smallest or largest value as the pivot. In these cases, the performance of the algorithm degrades since the algorithm can only recursively quicksort one sub-array instead of two.

 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: template void quick_sort (vector & v, int low, int high) {// Do not solve recursively when faced with // only 1 or 2 elements if (low == high) {return; } Else if (low + 1 == high) {if (v [low]> v [high]) {swap (v [low], v [high]); return; }} // Select pivot int middle = (low + high) / 2; T pivot = v [middle]; swap (v [middle], v [high]); // Partition int i; int j; for (i = low, j = high - 1;;) {while (v [i] Listing 1 A Quicksort implementation

A more advanced quicksort implementation appears on page 347 of the Weiss textbook. The Weiss implementation uses a different pivot and partition strategy known as median-of-three partitioning. This optimized strategy improves quicksort's performance by preventing the algorithm from selecting the minimum or maximum value as the pivot. This implementation also specifies a minimum array size that the algorithm will recursively operate on. When presented with a portion of an array that is smaller than this cut-off size, the Weiss quicksort implementation performs an insertion sort.

© um.co.ua - учбові матеріали та реферати