Learning Sorting

 Learning Sorting

  • Selection Sort
      1. Take an array as input and print it using a loop. a=[11,2,4,3,12]
      2. Find the smallest element and print it.  2
      3. Find the position of the smallest number and print it. 1
      4. Swap the smallest number with the 0th element. [11,2,4,3,12]=[2,11,4,3,12]
      5. Repeat for all numbers in the array.
  • Bubble Sort
      1. Take an array as input and print it using a loop. a=[11,2,4,3,12]
      2. Find numbers where left number is >neighboring right number
      3. Swap the out of order neighboring numbers.
      4. Repeat till array gets sorted

 

 

 

3 Comments

Piyush Maurya said…
arr=[11,2,4,3,12]
print("Array element is:")
for i in range(len(arr)):
print(arr[i])

# Find the smallest element and print it. 2
# Find the position of the smallest number and print it. 1

smallest=arr[0]
pos=0
for i in range(len(arr)):
if arr[i]<smallest:
smallest=arr[i]
pos=i
print("Smallest element in array is:",smallest)
print("Position of smallest element in array is:",pos)

# Swap the smallest number with the 0th element. [11,2,4,3,12]=[2,11,4,3,12]
arr[0],arr[pos]=arr[pos],arr[0]
print("Swapped Array:")
for i in range(len(arr)):
print(arr[i])
Coder said…
Complete Selection Sort.

a=[11,2,4,3,-2]
n=len(a)
# print(a,n)
for i in range(n):
# print(i,a[i])
min,minpos=a[i],i
for j in range(i,n ):
if a[j]<min:
min=a[j]
minpos=j
a[i],a[minpos]=a[minpos],a[i]
print (a)
Piyush Maurya said…
# Repeat for all numbers in the array.
a = [11, 2, 4, 3, -2]
n = len(a)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if a[j] < a[min_index]:
min_index = j
a[i], a[min_index] = a[min_index], a[i]
print(a)

Post a Comment

3 Comments

  1. arr=[11,2,4,3,12]
    print("Array element is:")
    for i in range(len(arr)):
    print(arr[i])

    # Find the smallest element and print it. 2
    # Find the position of the smallest number and print it. 1

    smallest=arr[0]
    pos=0
    for i in range(len(arr)):
    if arr[i]<smallest:
    smallest=arr[i]
    pos=i
    print("Smallest element in array is:",smallest)
    print("Position of smallest element in array is:",pos)

    # Swap the smallest number with the 0th element. [11,2,4,3,12]=[2,11,4,3,12]
    arr[0],arr[pos]=arr[pos],arr[0]
    print("Swapped Array:")
    for i in range(len(arr)):
    print(arr[i])

    ReplyDelete
  2. Complete Selection Sort.

    a=[11,2,4,3,-2]
    n=len(a)
    # print(a,n)
    for i in range(n):
    # print(i,a[i])
    min,minpos=a[i],i
    for j in range(i,n ):
    if a[j]<min:
    min=a[j]
    minpos=j
    a[i],a[minpos]=a[minpos],a[i]
    print (a)

    ReplyDelete
  3. # Repeat for all numbers in the array.
    a = [11, 2, 4, 3, -2]
    n = len(a)
    for i in range(n):
    min_index = i
    for j in range(i + 1, n):
    if a[j] < a[min_index]:
    min_index = j
    a[i], a[min_index] = a[min_index], a[i]
    print(a)

    ReplyDelete