nama = ('a', 'B', 'A')
for i in range(len(nama) - 1, 0, -1):
for j in range(i):
if nama[j] > nama[j + 1]:
temp2=nama[j]
nama[j]= nama[j+1]
nama[j+1]=temp2
print(nama)
Output code is
('A', 'B', 'a' )
How to covert output to('A', 'a', 'B')
with bubble sort?
Here https://www.geeksforgeeks.org/bubble-sort/ the bubble sorting algorithme in python to use it with strings you can make a dictionary with all characters and their values (you can put in the order you want 'a':1, 'A':2 etc...) if dic[arr[j]] > dic[arr[j+1]]:
or use the ord function which returns an interger representing the unicode char if ord(arr[j]) > ord(arr[j+1]):
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]),
You cant do that just because in ASCII ord('a') = 97 > ord('A')
and ord('a') > ord('B')
so if you use any sort operation for this list, it will always ['A','B','a']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.