Page 73 - Digicode_AI_class_8
P. 73
Sorting an Array
Sorting is the process of arranging items in a collection.
Consider an example: Have you seen how tailors arrange shirts in a cupboard, they always keep the
shirts in sorted order of size and thus when the tailor wants to place a new shirt, he will place it at
the right position very quickly by moving other shirts forward to keep the right place for a new shirt.
44 45 46 48 43
Sorted Unsorted
Consider the following array:
4 7 1 3 5 2 6
Here, the items are not arranged in any order.
1 2 3 4 5 6 7
Python has an inbuilt sort function (sort( ): to arrange the list in ascending order) to sort an array.
Example: numbers=[7,2,9,4]
numbers.sort()
Print(numbers)
Result:
[2,4,7,9]
Searching Elements In An Array
To search an element in an array, Python uses the indexing method.
Consider an array:
X=[“R”, “D”, “F”, “H”]
Print(x.index(“F”))
If you run the above code, you would get ‘2’ as output.
The index method works on numeric arrays too:
x=[1,6,5,3,4]
Print(x.index(5))
If you run the above code, you would get ‘2’ as output.
Information Literacy
code Quest Media Literacy
Fill in the blanks.
1. Array improves the of code by using a single variable for a large set
of data.
2. The variables in an array are ordered with the index starting from 0.
Advanced MakeCode Arcade 71

