Find index of first occurrence when an unsorted an array is sorted

Given an unsorted an array and a number x, find an index of first occurrence of x when we sort the array. If x is not present, print -1.

Examples:

Input : arr[] = {10, 30, 20, 50, 20}
           x = 20
Output : 1
Sorted an array is {10, 20, 20, 30, 50}

Input : arr[] = {10, 30, 20, 50, 20}
           x = 60
Output : -1
60 is not present in array.

A simple solution is to first sort the array, then do binary search to find first occurrence.

Implementation:

Python3

# Python3 program to find index of first
# occurrence of x when an array is sorted.
import math
def findFirst(arr, n, x):
    arr.sort()
    # lower_bound returns iterator pointing to
    # first element that does not compare less
    # to x.
    ptr = lowerBound(arr, 0, n, x)
    # If x is not present return -1.
    return 1 if (ptr != x) else (ptr - arr)
def lowerBound(a, low, high, element):
    while(low < high):
        middle = low + (high - low) // 2
        if(element > a[middle]):
            low = middle + 1
        else:
            high = middle
    return low
# Driver Code
if __name__ == '__main__':
    x = 20
    arr = [10, 30, 20, 50, 20]
    n = len(arr)
    print(findFirst(arr, n, x))
Output

1

An efficient solution is to simply count smaller elements than x.

Implementation:

Python3

# Python 3 program to find index
# of first occurrence of x when
# an array is sorted.
def findFirst(arr, n, x):
    count = 0
    isX = False
    for i in range(n):
        if (arr[i] == x):
            isX = True
        elif (arr[i] < x):
            count += 1
    return -1 if(isX == False) else count
# Driver Code
if __name__ == "__main__":
    x = 20
    arr = [10, 30, 20, 50, 20]
    n = len(arr)
    print(findFirst(arr, n, x))
Output
1

Explore More

Explain about Hugging Face Transformers

Hugging Face Transformers is a powerful library designed for natural language processing (NLP), computer vision, and audio tasks. It provides state-of-the-art pretrained models and tools for fine-tuning and deploying these

Python 10 Programs for Beginners

Program 1:Write a program to create a 2D array using NumPy. Output: Program 2: Write a program to convert a python list to a NumPy array. Output: Program 3: Write a program to create matrix of 3×3 from 11 to 30. Output: Program 4: Write a program to create a data frame to store data of candidates who appeared in

AI Roadmap using Python

Python is a great foundation for diving into AI! To take the next step in your AI learning journey, here’s a roadmap to guide you. 1. Strengthen Your Math Skills