因此,我决定通过创建另一个数组(让我们说长度为arraycount)与要排序的输入数组(让我们说长度为arraynumber)相同长度来解决这个问题。为了使程序真正检查排序功能的稳定性,我决定使用重复出现的整数数组的测试用例,例如arraynumber = {10,8,7,2,1,6}
。然后,我使用一个函数来计算数组中数字的出现并将其存储在arraycount[]
中,结果将为arraycount={1,3,1}
。
自然地,在按升序排序之后,它们变为arraynumber={1,6,10}
,并且arraycount的结果决定其稳定与否。因此,如果其稳定的arraycount={1,1}
则不会相同。
这是我一直在努力的代码。感谢您的帮助和反馈。主要功能和输入尚未使用。我将获取原始arraycount的另一个数组副本,然后将其进行比较以检查它是否保留了原始位置。对不起,如果我犯了任何小错误。谢谢。
def merge(arr1,l,m,r,arr2):
n1 = m - l + 1
n2 = r- m
# create temp arrays
L = [0] * (n1)
R = [0] * (n2)
# Copy data to temp arrays L[] and R[]
for i in range(0,n1):
L[i] = arr1[l + i]
for j in range(0,n2):
R[j] = arr1[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray
while i < n1 and j < n2 :
if L[i] <= R[j]:
arr1[k] = L[i]
arr2[k]=L[i]
i += 1
else:
arr1[k] = R[j]
arr2[k]=R[j]
j += 1
k += 1
# Copy the remaining elements of L[],if there
# are any
while i < n1:
arr1[k] = L[i]
arr2[k]=L[i]
i += 1
k += 1
# Copy the remaining elements of R[],if there
# are any
while j < n2:
arr1[k] = R[j]
arr2[k]=R[j]
j += 1
k += 1
# l is for left index and r is right index of the
# sub-array of arr to be sorted
def mergeSort(arr1,arr2):
if l < r:
# Same as (l+r)/2,but avoids overflow for
# large l and h
m = (l+(r-1))/2
# Sort first and second halves
mergeSort(arr1,arr2)
mergeSort(arr1,m+1,arr2)
merge(arr1,arr2)
# This function takes last element as pivot,places
# the pivot element at its correct position in sorted
# array,and places all smaller (smaller than pivot)
# to left of pivot and all greater elements to right
# of pivot
def partition(arr1,low,high,arr2):
i = ( low-1 ) # index of smaller element
pivot = arr1[high] # pivot
for j in range(low,high):
# If current element is smaller than or
# equal to pivot
if arr1[j] <= pivot:
# increment index of smaller element
i = i+1
arr1[i],arr1[j] = arr1[j],arr1[i]
arr2[i],arr2[j]=arr2[j],arr2[i]
arr1[i+1],arr1[high] = arr1[high],arr1[i+1]
arr2[i+1],arr2[high]=arr2[high],arr2[i+1]
return ( i+1 )
# The main function that implements QuickSort
# arr1[] --> Array to be sorted,# arr2[] --> Second Array of the count to be sorted along with first array
# low --> Starting index,# high --> Ending index
# Function to do Quick sort
def quickSort(arr1,arr2):
if low < high:
# pi is partitioning index,arr[p] is now
# at right place
pi = partition(arr1,arr2)
# Separately sort elements before
# partition and after partition
quickSort(arr1,pi-1,arr2)
quickSort(arr1,pi+1,arr2)
def countArray(arr1,arr2):
i=0,j=1,k=0
while i<range(len(arr1[])):
while j<range(len(arr1[])):
if arr1[i]==arr1[j]:
arr2[i]=k+1
j=j+1
k=0
i=i+1
arraylist=[]
arraycount=[]
def isStable(arr1,arr2):
k=0
while i < range(len(arr1[])):
if arr[i]==arr2[i]:
k=k+1
i=i+1
if k==len(arr2):
print("Stable sort")
else:
print("Unstable sort")