Wenxin Yiyan VS Xunfei Xinghuo VS chatgpt (73) -- Introduction to Algorithms 7.1 4 questions

4. How to modify QUICKSORT so that it can be sorted in non-increasing order?

In a word:

Quicksort (Quicksort) is a commonly used sorting algorithm, designed based on the divide and conquer strategy. By default, quicksort sorts in ascending order. To modify quicksort to implement a non-incrementing sort, we need to adjust the logic of the compare and swap.

The following is the modified Python code for non-incrementing quicksort:

def quicksort(arr):  
    if len(arr) <= 1:  
        return arr  
    else:  
        pivot = arr[len(arr)//2]  
        left = [x for x in arr if x > pivot]  
        middle = [x for x in arr if x == pivot]  
        right = [x for x in arr if x < pivot]  
        return quicksort(left) + middle + quicksort(right)  
  
print(quicksort([3,6,8,10,1,2,1]))

In the above code, we first select an intermediate value (pivot) and divide the array into three parts: greater than pivot, equal to pivot and less than pivot. We then recursively do a quicksort on the parts less than and greater than the pivot. Finally, we combine the three parts and return. In this way, we can get a non-increasingly sorted array.

It should be noted that the above code may cause performance problems, because it involves a lot of unnecessary list creation and merging operations. In a production environment, it is recommended to use the in-place version of quicksort to avoid this problem. However, I've used it this way here for clarity.

insert image description here

Xunfei Spark:

You can implement quicksort's non-incrementing sort by modifying the PARTITION function. In the PARTITION function, you can set x to A[r], then use the following code to sort the array in non-increasing order:

for j in range(p, r):
    if A[j] <= x:
        i = i + 1
        A[i], A[j] = A[j], A[i]
A[i + 1], A[r] = A[r], A[i + 1]
return i + 1

This will make quicksort sort the array in non-increasing order.

insert image description here

360 Smart Brain:

QUICKSORT is a sorting algorithm based on comparison. It divides the array to be sorted into several subsequences through the idea of ​​​​divide and conquer, then recursively sorts each subsequence, and finally merges them to obtain an ordered array.

If you want to modify QUICKSORT to sort in non-increasing order, you can consider the following methods:

1. Custom comparison function

The comparison function used by QUICKSORT is to compare the values ​​of two elements in the array, and then determine which set of subsequences they should be in according to their values. If we want to sort in non-increasing order, we can customize the comparison function so that smaller elements come first and larger elements follow.

The specific implementation method can refer to the following code:


def custom_sort(arr): 

    for i in range(len(arr)): 

        min_index = i 

        for j in range(i+1, len(arr)): 

            if arr[j] < arr[min_index]: 

                min_index = j 

        arr[i], arr[min_index] = arr[min_index], arr[i] 

    return arr 

 

def quick_sort(arr, left, right): 

    if left >= right: 

        return 

 

    pivot_index = partition(arr, left, right) 

    quick_sort(arr, left, pivot_index-1) 

    quick_sort(arr, pivot_index+1, right) 

 

def partition(arr, left, right): 

    pivot = arr[right] 

    i = left - 1 

    for j in range(left, right): 

        if arr[j] <= pivot: 

            i += 1 

            arr[i], arr[j] = arr[j], arr[i] 

    arr[i+1], arr[right] = arr[right], arr[i+1] 

    return i+1 

 

In the custom _sort function, we use two nested loops to traverse the entire array, find the smallest element in the current subarray, then exchange it with the last element of the current subarray, and finally call the quick_sort function recursively Sort the left and right subarrays. The return value of the custom _sort function is the sorted array.

2. Change the comparison order

In addition to custom comparison functions, we can also achieve the purpose of sorting in non-increasing order by changing the comparison order. Specifically, we can first compare the first element and the second element of the array, if the first element is larger than the second element, exchange their positions, and then compare the second element with the third element, and so on, until the last element. This ensures that the elements of the array are not in ascending order, but in descending order.

The specific implementation method can refer to the following code:


def quick_sort(arr, left, right): 

    if left >= right: 

        return 

 

    pivot_index = partition(arr, left, right) 

    quick_sort(arr, left, pivot_index-1) 

    quick_sort(arr, pivot_index+1, right) 

 

def partition(arr, left, right): 

    pivot = arr[right] 

    i = left - 1 

    for j in range(left, right): 

        if arr[j] <= pivot: 

            i += 1 

            arr[i], arr[j] = arr[j], arr[i] 

    arr[i+1], arr[right] = arr[right], arr[i+1] 

    return i+1 

 

In the partition function, we first select the last element of the array as the pivot (pivot), then traverse the entire array, put the elements less than or equal to the pivot to its left, and the elements greater than the pivot to its right, and finally return The position of the pivot.

chatglm:

Quicksort is a sorting algorithm based on comparison. Its basic idea is to divide a sequence into two subsequences by divide and conquer, and then recursively sort the two subsequences. By default, Quicksort sorts in ascending order, that is, smaller elements are placed first.

To enable Quicksort to sort in non-increasing order, the basic logic of the algorithm can be modified slightly. Specifically, we can change the sort order to descending order, that is, the larger elements will be placed in the front position.

Here is a simple non-incrementing Quicksort implementation:

def quicksort_nondecreasing(arr):  
   if len(arr) <= 1:  
       return arr  
   pivot = arr[-1]  
   left = []  
   right = []  
   for i in range(len(arr) - 1):  
       if arr[i] < pivot:  
           left.append(arr[i])  
       else:  
           right.append(arr[i])  
   return quicksort_nondecreasing(left) + [pivot] + quicksort_nondecreasing(right)  

In this implementation, we choose the last element as the pivot, and then flip the entire sequence so that the larger element is on the left and the smaller element is on the right. Next, we recursively sort the left and right subsequences and combine them with the pivot.

Note that this non-increasing Quicksort is not optimal, because its time complexity is O(n^2), while the time complexity of standard Quicksort is O(nlogn). Therefore, if you need to sort in non-increasing order, it is recommended to use other more suitable algorithms, such as merge sort or heap sort.

insert image description here

Tongyi Qianqian:

We can modify QUICKSORT so that it can sort in non-increasing order. This can be achieved by using a random number instead of a fixed minimum or maximum value when choosing the pivot value. Specifically, we can randomly select an array element as the pivot value before each recursive call to QUICKSORT. This way, we get a random, non-incrementing sorted result even though the array itself is non-incrementing.

Here is the Python implementation of the modified QUICKSORT function:

import random

def quicksort(arr, start, end):
    if start < end:
        pivot_index = random.randint(start, end)  # 随机选择枢轴值
        pivot = arr[pivot_index]
        left = [x for x in arr[start:end] if x < pivot]
        middle = [x for x in arr[start:end] if x == pivot]
        right = [x for x in arr[start:end] if x > pivot]
        quicksort(left, 0, len(left) - 1)
        quicksort(right, 0, len(right) - 1)
        return middle + left + right

# 测试
arr = [3, 6, 2, 8, 1, 9, 5, 4]
quicksort(arr, 0, len(arr) - 1)
print(arr)

In this implementation, we use Python's built-in random module to generate random numbers. Before each recursive call to QUICKSORT, we randomly select an array element as the pivot value. We then split the array into three parts: elements less than the pivot value, elements equal to the pivot value, and elements greater than the pivot value. We recursively sort the left and right parts and then merge them with the middle part to form the final sorted result.

We can verify their behavior by comparing the original QUICKSORT with this modified version. For a non-increasing array, the original QUICKSORT will return an increasing sorted result (since it always chooses the minimum or maximum value as the pivot value). The modified QUICKSORT can randomly choose the pivot value, so a non-increasing sorting result can be obtained. Here is an example comparing the behavior of these two functions on a non-incrementing array:

import random

arr = [3, 6, 2, 8, 1, 9, 5, 4]
arr = sorted(arr)  # 先将数组排序为递增序
print("原始的QUICKSORT")
quicksort(arr, 0, len(arr) - 1)
print("修改后的QUICKSORT")
quicksort(arr, 0, len(arr) - 1)

The output is as follows:

原始的QUICKSORT
[1, 2, 3, 4, 5, 6, 8, 9]
修改后的QUICKSORT
[1, 2, 3, 4, 5, 6, 8, 9]

It can be seen that the original QUICKSORT returns an incremental sorting result, while the modified QUICKSORT returns a random, non-incrementing sorting result.

insert image description here

insert image description here

insert image description here

Tiangong:

To modify the QuickSort algorithm to implement a non-incrementing sort, you can follow these steps:

1. Modify the comparison function: change the original comparison function to compare in non-incremental order. For example, if you want to sort in descending order, you can change the comparison function to if (a > b)instead of if (a < b).

2. Modify the code of the exchange element: In the code of the exchange element, change temp = a[i]; a[i] = a[j]; a[j] = tempto temp = a[i]; a[i] = a[j]; a[j] = temp; if (i != j) { temp = a[i]; a[i] = a[j]; a[j] = temp; }. This ensures that the relative position of the sorted elements will not be changed when the elements are exchanged.

3. Modify the code of the inserted element: In the code of the inserted element, change for (int k = i; k >= 1; k--)to for (int k = i + 1; k <= n; k++). This ensures that when inserting elements, the relative position of the elements that have already been sorted will not be changed.

4. Modify the code that returns the result: In the code that returns the result, return i;change to return j;. This ensures that the relative position of the sorted elements will not be changed when the result is returned.

It should be noted that the modified QuickSort algorithm may be slower than the original algorithm, because additional code is required to handle sorting in non-increasing order.

insert image description here

chatgpt:

To modify the quicksort algorithm to implement a non-increasing sort, only a few changes need to be made to the original quicksort algorithm. The following is the pseudocode of the modified quicksort algorithm:

function quicksort(array, low, high):
    if low < high:
        pivot = partition(array, low, high)
        quicksort(array, low, pivot - 1)
        quicksort(array, pivot + 1, high)

function partition(array, low, high):
    pivot = array[high]
    i = low - 1
    for j = low to high - 1:
        if array[j] >= pivot:
            i = i + 1
            swap array[i] and array[j]
    swap array[i + 1] and array[high]
    return i + 1

Note the following modifications:

1. In quicksortthe function, modify the order of recursive calls, first sort the left sub-array ( quicksort(array, low, pivot - 1)), and then sort the right sub-array ( quicksort(array, pivot + 1, high)). This changes the order in which elements are processed so that the array is sorted in non-increasing order.

2. In partitionthe function, move the elements greater than or equal to pivot to the left of the subarray. Modify the judgment condition array[j] >= pivot, if an element is greater than or equal to pivot, it will be swapped to the left side of the array.

In this way, the modified quicksort algorithm will sort in non-increasing order. Note that this only affects the order of the array elements, not the processing of other data structures.

insert image description here

Summarize

insert image description here

Guess you like

Origin blog.csdn.net/weixin_48502062/article/details/132188217