Find index of first occurrence when an unsorted array is sorted
Last Updated :
11 Jul, 2025
Given an unsorted 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 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:
C++
// C++ program to find index of first
// occurrence of x when array is sorted.
#include <bits/stdc++.h>
using namespace std;
int findFirst(int arr[], int n, int x)
{
sort(arr, arr + n);
// lower_bound returns iterator pointing to
// first element that does not compare less
// to x.
int* ptr = lower_bound(arr, arr + n, x);
// If x is not present return -1.
return (*ptr != x) ? -1 : (ptr - arr);
}
int main()
{
int x = 20, arr[] = { 10, 30, 20, 50, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findFirst(arr, n, x);
return 0;
}
Java
// Java program to find index of first
// occurrence of x when array is sorted.
import java.util.*;
class GFG {
static int findFirst(int arr[], int n, int x)
{
Arrays.sort(arr);
// lower_bound returns iterator pointing to
// first element that does not compare less
// to x.
int ptr = lowerBound(arr, 0, n, x);
// If x is not present return -1.
return (arr[ptr] != x) ? -1 : (ptr);
}
static int lowerBound(int[] a, int low, int high,
int element)
{
while (low < high) {
int middle = low + (high - low) / 2;
if (element > a[middle])
low = middle + 1;
else
high = middle;
}
return low;
}
// Driver Code
public static void main(String[] args)
{
int x = 20, arr[] = { 10, 30, 20, 50, 20 };
int n = arr.length;
System.out.println(findFirst(arr, n, x));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to find index of first
# occurrence of x when 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))
# This code is contributed by Rajput-Ji
C#
// C# program to find index of first
// occurrence of x when array is sorted.
using System;
class GFG {
static int findFirst(int[] arr, int n, int x)
{
Array.Sort(arr);
// lower_bound returns iterator pointing to
// first element that does not compare less
// to x.
int ptr = lowerBound(arr, 0, n, x);
// If x is not present return -1.
return (arr[ptr] != x) ? -1 : (ptr);
}
static int lowerBound(int[] a, int low, int high,
int element)
{
while (low < high) {
int middle = low + (high - low) / 2;
if (element > a[middle])
low = middle + 1;
else
high = middle;
}
return low;
}
// Driver Code
static public void Main()
{
int x = 20;
int[] arr = { 10, 30, 20, 50, 20 };
int n = arr.Length;
Console.Write(findFirst(arr, n, x));
}
}
// This code is contributed by ajit.
PHP
<?php
//PHP program to find index of first
// occurrence of x when array is sorted.
function findFirst( $arr, $n, $x)
{
sort($arr);
// lower_bound returns iterator pointing to
// first element that does not compare less
// to x.
$ptr = floor($arr);
// If x is not present return -1.
return ($ptr != $x)? 1 : ($ptr - $arr);
}
//Code driven
$x = 20;
$arr = array(10, 30, 20, 50, 20);
$n = sizeof($arr)/sizeof($arr[0]);
echo findFirst($arr, $n, $x);
#This code is contributed by Tushil.
?>
JavaScript
<script>
// Javascript program to find index of first
// occurrence of x when array is sorted.
function findFirst(arr, n, x)
{
arr.sort();
// lower_bound returns iterator pointing
// to first element that does not compare
// less to x.
let ptr = lowerBound(arr, 0, n, x);
// If x is not present return -1.
return (arr[ptr] != x) ? -1 : (ptr);
}
function lowerBound(a, low, high, element)
{
while (low < high)
{
let middle = low + parseInt(
(high - low) / 2, 10);
if (element > a[middle])
low = middle + 1;
else
high = middle;
}
return low;
}
// Driver code
let x = 20;
let arr = [ 10, 30, 20, 50, 20 ];
let n = arr.length;
document.write(findFirst(arr, n, x));
// This code is contributed by mukesh07
</script>
Complexity Analysis:
- Time Complexity : O(n Log n)
- Auxiliary Space: O(1)
An efficient solution is to simply count smaller elements than x.
Implementation:
C++
// C++ program to find index of first
// occurrence of x when array is sorted.
#include <bits/stdc++.h>
using namespace std;
int findFirst(int arr[], int n, int x)
{
int count = 0;
bool isX = false;
for (int i = 0; i < n; i++) {
if (arr[i] == x)
isX = true;
else if (arr[i] < x)
count++;
}
return (isX == false) ? -1 : count;
}
int main()
{
int x = 20, arr[] = { 10, 30, 20, 50, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findFirst(arr, n, x);
return 0;
}
Java
// Java program to find index of first
// occurrence of x when array is sorted.
public class GFG {
static int findFirst(int arr[], int n, int x)
{
int count = 0;
boolean isX = false;
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
isX = true;
}
else if (arr[i] < x) {
count++;
}
}
return (isX == false) ? -1 : count;
}
// Driver main
public static void main(String[] args)
{
int x = 20, arr[] = { 10, 30, 20, 50, 20 };
int n = arr.length;
System.out.println(findFirst(arr, n, x));
}
}
/*This code is contributed by PrinciRaj1992*/
Python3
# Python 3 program to find index
# of first occurrence of x when
# 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
# by ChitraNayal
C#
// C# program to find index of first
// occurrence of x when array is sorted.
using System;
public class GFG {
static int findFirst(int[] arr, int n, int x)
{
int count = 0;
bool isX = false;
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
isX = true;
}
else if (arr[i] < x) {
count++;
}
}
return (isX == false) ? -1 : count;
}
// Driver main
public static void Main()
{
int x = 20;
int[] arr = { 10, 30, 20, 50, 20 };
int n = arr.Length;
Console.WriteLine(findFirst(arr, n, x));
}
}
/*This code is contributed by PrinciRaj1992*/
PHP
<?php
// PHP program to find index of first
// occurrence of x when array is sorted.
function findFirst($arr, $n, $x)
{
$count = 0;
$isX = false;
for ($i = 0; $i < $n; $i++)
{
if ($arr[$i] == $x)
$isX = true;
else if ($arr[$i] < $x)
$count++;
}
return ($isX == false)? -1 : $count;
}
// Driver Code
$x = 20;
$arr = array(10, 30, 20, 50, 20);
$n = sizeof($arr);
echo findFirst($arr, $n, $x);
// This code is contributed
// by Akanksha Rai
?>
JavaScript
<script>
// JavaScript program to find index of first
// occurrence of x when array is sorted.
function findFirst(arr, n, x)
{
var count = 0;
var isX = false;
for(var i = 0; i < n; i++)
{
if (arr[i] == x)
{
isX = true;
}
else if (arr[i] < x)
{
count++;
}
}
return (isX == false) ? -1 : count;
}
// Driver Code
var x = 20, arr = [ 10, 30, 20, 50, 20 ];
var n = arr.length;
document.write(findFirst(arr, n, x));
// This code is contributed by Khushboogoyal499
</script>
Complexity Analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(1)
Similar Reads
Find the Kth occurrence of an element in a sorted Array Given a sorted array arr[] of size N, an integer X, and a positive integer K, the task is to find the index of Kth occurrence of X in the given array. Examples: Input: N = 10, arr[] = [1, 2, 3, 3, 4, 5, 5, 5, 5, 5], X = 5, K = 2Output: Starting index of the array is '0' Second occurrence of 5 is at
15+ min read
Find the index of first 1 in a sorted array of 0's and 1's Given a sorted array consisting 0's and 1's. The problem is to find the index of first '1' in the sorted array. It could be possible that the array consists of only 0's or only 1's. If 1's are not present in the array then print "-1". Examples : Input : arr[] = {0, 0, 0, 0, 0, 0, 1, 1, 1, 1}Output :
15 min read
Find the index of first 1 in an infinite sorted array of 0s and 1s Given an infinite sorted array consisting 0s and 1s. The problem is to find the index of first â1â in that array. As the array is infinite, therefore it is guaranteed that number '1' will be present in the array. Examples: Input : arr[] = {0, 0, 1, 1, 1, 1} Output : 2 Input : arr[] = {1, 1, 1, 1,, 1
9 min read
Sort an array in descending order based on the sum of its occurrence Given an unsorted array of integers which may contain repeated elements, sort the elements in descending order of some of its occurrence. If there exists more than one element whose sum of occurrences are the same then, the one which is greater will come first. Examples: Input: arr[] = [2, 4, 1, 2,
7 min read
Sort an array in descending order based on the sum of its occurrence Given an unsorted array of integers which may contain repeated elements, sort the elements in descending order of some of its occurrence. If there exists more than one element whose sum of occurrences are the same then, the one which is greater will come first. Examples: Input: arr[] = [2, 4, 1, 2,
7 min read
Find the only missing number in a sorted array You are given a sorted array of N integers from 1 to N with one number missing find the missing number Examples: Input :ar[] = {1, 3, 4, 5}Output : 2Input : ar[] = {1, 2, 3, 4, 5, 7, 8}Output : 6A simple solution is to linearly traverse the given array. Find the point where current element is not on
9 min read