1. After sorting n elements from large to small, select the K-Large element
#!/usr/bin/env python#Coding-*-Utf:8-*-#bubble Sort Select K elementImportRandomImport TimedefSelect_k (): N= Int (Input ("The length of the array to be generated:")) Arraya= [] forIinchrange (N): x= Random.choice (Range (100)) arraya.append (x)Print("the resulting array (not sorted):", Arraya) Arrayb=Bubble_sort (Arraya)Print("sorted Array:", Arrayb) k= Int (Input ("Select the first few elements:")) #from large to small k elementsresult = Arrayb[k-1] returnresultdefBubble_sort (a): forIinchRange (len (a)): forJinchRange (I,len (a)):ifa[i]<A[j]: tmp=A[i] A[i]=A[j] A[j]=tmpreturnaif __name__=='__main__': T0=Time.clock ()Print("The first k elements are:", Select_k ())#the second call to clock () minus the first call to clock () is the time that the program executes Print("Time of program execution:", Time.clock ()-t0)
2. bubble sort before K elements, the following elements are compared with the K element, if less than ignore, if greater than add to the correct position and remove the last element
#!/usr/bin/env python#Coding-*-Utf:8-*-#bubble Sort before the k elements, followed by the elements are compared to the K-element, if less than ignored, if greater than#add to the correct position and remove the last elementImportRandomImport TimedefSelect_k (): N= Int (Input ("The length of the array to be generated:")) K= Int (Input ("Select the first few elements:")) Arraya= [] forIinchrange (N): x= Random.choice (Range (100)) arraya.append (x)Print("the resulting array (not sorted):", Arraya) Arrayb=Bubble_sort (arraya[:k])Print("array of first k elements sorted:", Arrayb) forIinchRange (k, n):if(arrayb[-1]<Arraya[i]): Arrayb.append (Arraya[i]) Arrayb=Bubble_sort (Arrayb) arrayb.pop ()#returns the first K-Large elementresult = Arrayb[-1] returnresultdefBubble_sort (a): forIinchRange (len (a)): forJinchRange (I,len (a)):ifa[i]<A[j]: tmp=A[i] A[i]=A[j] A[j]=tmpreturnaif __name__=='__main__': T0=Time.clock ()Print("the K-large elements are:", Select_k ())#the second call to clock () minus the first call to clock () is the time that the program executes Print("Time of program execution:", Time.clock ()-t0)
3. Time Comparison
Method One:
N | 10 | 100 | 1000 | 5000 | 10000 | 20000 |
T | 0.0 | 0.001 | 0.06 | 1.17 | 4.65 | 18.25 |
Method Two:
N | 10 | 100 | 1000 | 5000 | 10000 | 20000 |
T | 0.0 | 0.0 | 0.0 | 0.02 | 0.02 | 0.03 |
Algorithm: Bubble sort (python version)