Page 66 - Computer Genius Class 07
P. 66

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 o  si e and thus  hen the tailor  ants to place a ne  shirt  he  ill place it at
                  the right position very quickly by moving other shirts forward to keep the right place for a new shirt.








                                                                   46
                                                                              48
                                           44          45          46         48            43
                                                       45
                                           44
                                                             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
                   ython has an in uilt sort  unction  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
                         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.




                       64    Computer Genius-VII
   61   62   63   64   65   66   67   68   69   70   71