Saturday, December 28, 2024
Google search engine
HomeLanguagesPython | Check if list is sorted or not

Python | Check if list is sorted or not

The sorted operation of list is essential operation in many application. But it takes best of O(nlogn) time complexity, hence one hopes to avoid this. So, to check if this is required or not, knowing if list is by default sorted or not, one can check if list is sorted or not. Lets discuss various ways this can be achieved. 
Method #1 : Naive method The simplest way to check this is run a loop for first element and check if we could find any smaller element than it after that element, if yes, the list is not sorted. 
 

Python3




# Python3 code to demonstrate
# to check if list is sorted
# using naive method
 
# initializing list
test_list = [1, 4, 5, 8, 10]
 
# printing original list
print ("Original list : " + str(test_list))
 
# using naive method to
# check sorted list
flag = 0
i = 1
while i < len(test_list):
    if(test_list[i] < test_list[i - 1]):
        flag = 1
    i += 1
     
# printing result
if (not flag) :
    print ("Yes, List is sorted.")
else :
    print ("No, List is not sorted.")


Output :

Original list : [1, 4, 5, 8, 10]
Yes, List is sorted.

Method #2 : Using sort() The new list can be made as a copy of the original list, sorting the new list and comparing with the old list will give us the result if sorting was required to get sorted list or not. 
 

Python3




# Python3 code to demonstrate
# to check if list is sorted
# using sort()
 
# initializing list
test_list = [10, 4, 5, 8, 10]
 
# printing original list
print ("Original list : " + str(test_list))
 
# using sort() to
# check sorted list
flag = 0
test_list1 = test_list[:]
test_list1.sort()
if (test_list1 == test_list):
    flag = 1
     
# printing result
if (flag) :
    print ("Yes, List is sorted.")
else :
    print ("No, List is not sorted.")


Output :

Original list : [10, 4, 5, 8, 10]
No, List is not sorted.

Method #3 : Using sorted() Using the similar analogy as the above method, but does not create a new space, but just a momentary space for that time and hence useful, shorter and faster method than above. 
 

Python3




# Python3 code to demonstrate
# to check if list is sorted
# using sorted()
 
# initializing list
test_list = [1, 4, 5, 8, 10]
 
# printing original list
print ("Original list : " + str(test_list))
 
# using sorted() to
# check sorted list
flag = 0
if(test_list == sorted(test_list)):
    flag = 1
     
# printing result
if (flag) :
    print ("Yes, List is sorted.")
else :
    print ("No, List is not sorted.")


Output :

Original list : [1, 4, 5, 8, 10]
Yes, List is sorted.

Method #4 : Using all() Most elegant, pythonic and faster way to check for sorted list is the use of all(). This uses the similar method as naive, but use of all() make it quicker. 
 

Python3




# Python3 code to demonstrate
# to check if list is sorted
# using all()
 
# initializing list
test_list = [9, 4, 5, 8, 10]
 
# printing original list
print ("Original list : " + str(test_list))
 
# using all() to
# check sorted list
flag = 0
if(all(test_list[i] <= test_list[i + 1] for i in range(len(test_list)-1))):
    flag = 1
     
# printing result
if (flag) :
    print ("Yes, List is sorted.")
else :
    print ("No, List is not sorted.")


Output :

Original list : [9, 4, 5, 8, 10]
No, List is not sorted.

Method #5 : Use the zip() function and the all() function

One approach that could be used to check if a list is sorted or not is to use the zip() function and the all() function. This approach involves pairing up the elements of the list in pairs using zip(), and then using all() to check if the elements of each pair are in the correct order.

Here is an example of how this approach could be implemented:

Python3




# initialize the list
test_list = [1, 4, 5, 8, 10]
 
# check if the list is sorted using zip() and all()
is_sorted = all(a <= b for a, b in zip(test_list, test_list[1:]))
 
# print the result
if is_sorted:
    print("Yes, the list is sorted.")
else:
    print("No, the list is not sorted.")
#This code is contributed by Edula Vinay Kumar Reddy


Output

Yes, the list is sorted.

The auxiliary space complexity of the zip() and all() approach to checking if a list is sorted is O(1), as it does not require any additional space to store data beyond the original list.

The time complexity of this approach is O(n), as it involves iterating through the elements of the list once to check if they are in the correct order.

Method #6: Use the numpy library:

  1. Import the numpy library
  2. Initialize the list
  3. Convert the list to a numpy array using numpy.array() method
  4. Use numpy.all() method to check if the numpy array is sorted or not
  5. Print the result

Python3




# importing numpy library
import numpy as np
 
# initializing list
test_list = [1, 4, 5, 8, 10]
 
# convert list to numpy array
test_arr = np.array(test_list)
 
# check if the numpy array is sorted or not
if np.all(np.diff(test_arr) >= 0):
    print("Yes, List is sorted.")
else:
    print("No, List is not sorted.")


Output:

Yes, List is sorted.

Time Complexity: O(n)
The time complexity of this approach is O(n), where n is the length of the list. This is because we are only performing a single pass over the numpy array to check if it is sorted or not.

Space Complexity: O(n)
The space complexity of this approach is also O(n), as we are creating a numpy array of the same size as the input list.

RELATED ARTICLES

Most Popular

Recent Comments