मराठी

Accept a list containing numbers. Sort the list using any sorting technique. Thereafter accept a number and display the position where that number is found.

Advertisements
Advertisements

प्रश्न

Accept a list containing numbers. Sort the list using any sorting technique. Thereafter accept a number and display the position where that number is found. Also display suitable message, if the number is not found in the list.

कोड लेखन
Advertisements

उत्तर

The list is first sorted using selection sort. Then binary search finds the required number efficiently. Positions displayed are 1-based.

def selection_sort(numbers):
    for i in range(len(numbers) - 1):
        minimum_index = i

        for j in range(i + 1, len(numbers)):
            if numbers[j] < numbers[minimum_index]:
                minimum_index = j

        numbers[i], numbers[minimum_index] = (
            numbers[minimum_index], numbers[i]
        )

    return numbers


def binary_search(numbers, target):
    low = 0
    high = len(numbers) - 1

    while low <= high:
        mid = (low + high) // 2

        if numbers[mid] == target:
            return mid + 1  # 1-based position
        if numbers[mid] < target:
            low = mid + 1
        else:
            high = mid - 1

    return -1


numbers = list(map(int, input("Enter list elements: ").split()))
selection_sort(numbers)
print("Sorted list:", numbers)

target = int(input("Enter number to search: "))
position = binary_search(numbers, target)

if position == -1:
    print("Number not found in the list")
else:
    print("Number found at position", position)

Enter list elements: 24 5 18 9 30
Sorted list: [5, 9, 18, 24, 30]
Enter number to search: 18
Number found at position 3
 
shaalaa.com
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 5: Liner List Manipulation - EXERCISE [पृष्ठ १०५]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
पाठ 5 Liner List Manipulation
EXERCISE | Q 18. | पृष्ठ १०५
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×