Skip to main content

Featured

Write a Python Program to find palindrome of a given string

If you reverse the word then you get the same word that word is palindrome. def   palindrome ( str ):     pointer =  str       rev_str =  reversed (pointer)       if   list (pointer) ==  list (rev_str):         print ( "It is palindrome" )       else :         print ( "It is not palindrome" )  palindrome( 'level' ) palindrome( 'madam' ) palindrome( 'life' ) palindrome( 'refer' ) Output:  It is palindrome It is palindrome It is not palindrome It is palindrome

Selection sort in python

 Selection sort is more advanced and faster than bubble sort.

In bubble sort swapping in done in every iteration every time but in selection sort swapping will done only once in one iteration it will help the cpu to run and execute the program more faster.

In selection sort after every iteration one number will be sorted. When all numbers are sorted then you get a sorted list.

Algorithm:

1) lets assume element in index 0 as min 

2) Now compare min with al other elements

3) If an element is lesser than min then swap

4) Now the element present in index 0 is sorted and others are unsorted

5) Now assume element in index 1 as min and repeat step 3,4 and 5

6) Repeat untill list is sorted

Best time complexity: 0[n^2]

Average time complexity: 0[n^2]

Worst time complexity: 0[n^2]

Now lets see working process:

Take list as  [61, 3, 43, 25, 16] same used in bubble sort

1) Iteration:

Min= 61(index 0)

Compare with every element

 Swap 61 and 3

2) Iteration: [3,61,43,25,16]

Min = 61(index 1)

Compare with every element

 Swap 61 and 16

3) Iteration: [3,16,43,25,61]

Min = 43(index 2)

Compare with every element

Swap 25 and 43

4) Iteration: [3,16,25,43,61]

Min = 43(index 3)

Compare with every element

No swapping

So the sorted list is [3, 16, 25, 43, 61]

Example:

[61, 2, 43, 25, 16, 34, 7]

Selection sort


Code for selection sort:

# Selection sort in Python

def selectionSort(arraysize):
   
    for i in range(size):
        min = i

        for j in range(i + 1, size):
         
    
            if array[j] < array[min]:
                min = j
         
        # put min at the correct position
        (array[i], array[min]) = (array[min], array[i])


list = [2,78,23,4,21,15,9]
size = len(list)
print(' Before sorting :',list)
selectionSort(list, size)

print('After sorting :',list)

Output:

Before sorting : [2, 78, 23, 4, 21, 15, 9] After sorting : [2, 4, 9, 15, 21, 23, 78]


Hope you understand the program and try yourself for more clear view ,feel free to comment your thoughts!!    

Comments

Popular Posts