鱼C论坛

 找回密码
 立即注册
查看: 3205|回复: 3

sorting

[复制链接]
发表于 2023-10-12 15:24:17 | 显示全部楼层
Sure, I can help with that. Here's a Python function that uses the quicksort algorithm with a median partition scheme. The function sorts a list of floats in-place. If the reverse parameter is set to True, the list is sorted in descending order.

  1. def median_quicksort(arr, low=0, high=None, reverse=False):
  2.     if high is None:
  3.         high = len(arr) - 1
  4.     if low < high:
  5.         pi = partition(arr, low, high)
  6.         median_quicksort(arr, low, pi - 1, reverse)
  7.         median_quicksort(arr, pi + 1, high, reverse)
  8.     if reverse:
  9.         arr.reverse()

  10. def partition(arr, low, high):
  11.     median = sorted([arr[low], arr[high], arr[(low + high) // 2]])[1]
  12.     pivot_index = arr.index(median)
  13.     arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
  14.     i = low - 1
  15.     for j in range(low, high):
  16.         if arr[j] <= arr[high]:
  17.             i = i + 1
  18.             arr[ i], arr[j] = arr[j], arr[ i]
  19.     arr[i + 1], arr[high] = arr[high], arr[i + 1]
  20.     return i + 1
复制代码


Here's how you can use the function:

  1. arr = [10.1, 7.9, 8.2, 9.3, 6.5]
  2. median_quicksort(arr)
  3. print(arr)  # Output: [6.5, 7.9, 8.2, 9.3, 10.1]

  4. arr = [10.1, 7.9, 8.2, 9.3, 6.5]
  5. median_quicksort(arr, reverse=True)
  6. print(arr)  # Output: [10.1, 9.3, 8.2, 7.9, 6.5]
复制代码


This function works by first partitioning the array so that elements less than the pivot are to the left of the pivot and elements greater than the pivot are to the right. The pivot is chosen as the median of the first, middle, and last elements of the array. This process is then recursively applied to the sub-arrays to the left and right of the pivot. If reverse is True, the array is reversed at the end to give a descending sort.
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-28 05:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表