Random selection of the kth small element, random quick sorting-algorithm design and analysis experiment 4

1 question

Randomly select the kth smallest element, random quick sort

2 problem analysis

Randomize the operation of the selection of reference elements, and use the Sherwood algorithm to improve the average computing performance with a high probability

3 Problem Modeling

Enter the sequence to be sorted and randomly select the reference element

4 Algorithm description

Before a division, the Sherwood-type probability algorithm randomly determines a record in the sequence to be divided according to the random number as the axis value, and exchanges it with the first record. After one division, two subsequences expected to be balanced are obtained, so that The behavior of the algorithm is not affected by different input instances of the sequence to be sorted, so that the worst-case time performance of quicksort approaches the average-case time performance.

5 algorithm source code

import random
def random_quicksort(a,left,right):
    if(left<right):
        mid = random_partition(a,left,right)
        random_quicksort(a,left,mid-1)
        random_quicksort(a,mid+1,right)


def random_partition(a,left,right):
    t = random.randint(left,right)     #生成[left,right]之间的一个随机数
    a[t],a[right] = a[right],a[t]
    x = a[right]
    i = left-1                         #初始i指向一个空,保证0到i都小于等于 x
    for j in range(left,right):        #j用来寻找比x小的,找到就和i+1交换,保证i之前的都小于等于x
        if(a[j]<=x):
            i = i+1
            a[i],a[j] = a[j],a[i]
    a[i+1],a[right] = a[right],a[i+1]  #0到i 都小于等于x ,所以x的最终位置就是i+1
    return i+1

while(True):
    try:
        s = input("输入待排序数组:\n")             #待排数组
        l =s.split()
        a = [int(t) for t in l]
        random_quicksort(a,0,len(a)-1)
        print ("排序后:")
        for item in a:
            print(item,end=' ')
        print("\n")
    except:
        break

6. Test data
13 21 9 2 4 45 32
7. Program running results
insert image description here

For more university coursework experiment training,
you can pay attention to the official account: Time Wood
Reply to related
keywords

Guess you like

Origin blog.csdn.net/qq_43374681/article/details/122381951