PYTHON DATA STRUCTURE

  

       PYTHON

       DATA STRUCTURE

 


       Answer the following questions

                                                              (4 marks)

 

       1.Write a Program for Bubble sort?

Bubble  sorting

For Example:

#Bubble sort method to short list elements in ascending order

N=(83,25,50,70,14,74,67,90)

for i in range (0,len(N)-1):

  for j in range (0,i+1):

     if N[j]>N[j+1]:

          temp=N[j]

          N[j]=N[j+1]

          N[j+1]=temp

print(N)

       2.Write a Program for Selection sort?

SELECTION SORT

#Selection sort method to sort list elements in ascending order

N=[83,25,50,70,14,74,67,90]

for i in range(0,len(N)-1):

      minpos=i

      for j in range(i+1,len(N)-1):

          if N[j]<N[minpos]:

              minpos=j

          temp=N[i]

          N[i]=N[minpos]

          N[minpos]=temp

else:

      print(N)

       3. Write a Program for Insertion sort?

INSERTION SORT:

#Insertion sort method to sort list elements is ascending order

N=[83,25,50,70,14,74,67,90]

for i in range (1,len(N)):

        curval=N(i)

        curpos=i

        while  curpose >0 and N[curpos-1]>curval:

              N[curpos]=N[curpos-1]

              curpos=curpos-1

              N[curpos]=curval

#this is else part of for loop.

#it execute at the end of for loop.

else:

      print(N)

       4. Write a Program for Binary Search?

Binary search:

Binary search will search the data in the middle of the interval ,first and last of every position.

#Binary search method to search data using midpoint

N=[3,5,7,8,8,11,23,45,56]

while True:

      find_num=int(input("enter number to find..."))

      first=0

      last=len(N)-1

      while first<=last:

            midpoint=(first+last)//2

            if N[midpoint]==find_num:

                print("found")

            break

      else:

        if find_num<N[midpoint]:

             last=midpoint-1

        else:

            first=midpoint+1

    else:

        print("The given is not in list")

      ch=raw_input("continue[y/n]..?")

    if ch in('y','Y'):

       continue

    else:

       break

 

No comments:

Post a Comment