English

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

Question

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.

Code Writing
Advertisements

Solution

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
  Is there an error in this question or solution?
Chapter 5: Liner List Manipulation - EXERCISE [Page 105]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 5 Liner List Manipulation
EXERCISE | Q 18. | Page 105
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×