Home > Back-end >  How to add Square Brackets into Sorted Array
How to add Square Brackets into Sorted Array

Time:09-17

Expected Output: Sorted Array in Ascending Order: [1, 2, 3, 6] My OutPut Sorted Array in Ascending Order: 2 4 6 8

def partition(arr,low,high):
   i = ( low-1 )
   pivot = arr[high]
   for j in range(low , high):
      if arr[j] <= pivot:
         i = i 1
         arr[i],arr[j] = arr[j],arr[i]
   arr[i 1],arr[high] = arr[high],arr[i 1]
   return ( i 1 )
# sort
def quickSort(arr,low,high):
   if low < high:
      # index
      pi = partition(arr,low,high)
      # sort the partitions
      quickSort(arr, low, pi-1)
      quickSort(arr, pi 1, high)
# main
arr = []
n = int(input("Enter no ofelements"))
print("enter elements")
for i in range(0, n):
    ele = int(input())
    arr.append(ele)
print("Unsorted Array")
print(arr)
n = len(arr)
quickSort(arr,0,n-1)
print ("Sorted Array in Ascending Order:")
for i in range(n):
   print (arr[i],end=" ")

Please let me know How i add Square Brackets into my Sorted Array.

CodePudding user response:

We can replace the last two lines :

for i in range(n):
   print (arr[i],end=" ")

by this :

print(arr)

Output :

Enter no ofelements4
enter elements
2
4
3
1
Unsorted Array
[2, 4, 3, 1]
Sorted Array in Ascending Order:
[1, 2, 3, 4]

So the code looks like :

def partition(arr,low,high):
   i = ( low-1 )
   pivot = arr[high]
   for j in range(low , high):
      if arr[j] <= pivot:
         i = i 1
         arr[i],arr[j] = arr[j],arr[i]
   arr[i 1],arr[high] = arr[high],arr[i 1]
   return ( i 1 )
# sort
def quickSort(arr,low,high):
   if low < high:
      # index
      pi = partition(arr,low,high)
      # sort the partitions
      quickSort(arr, low, pi-1)
      quickSort(arr, pi 1, high)
# main
arr = []
n = int(input("Enter no ofelements"))
print("enter elements")
for i in range(0, n):
    ele = int(input())
    arr.append(ele)
print("Unsorted Array")
print(arr)
n = len(arr)
quickSort(arr,0,n-1)
print ("Sorted Array in Ascending Order:")
print(arr)
  • Related