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))
# This code is contributed
Output
1

Explore More

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

Find sum non repeating distinct elements array

Find sum of non-repeating (distinct) elements in an array Given an integer an array with repeated elements, the task is to find the sum of all distinct elements in the

Find the only different element in an array

Find the just distinct element in an array Given an array of integers where all elements are same except one element, find the just distinct element in the array. It