Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find position of element in unsorted array after it gets sorted

Tags:

c++

algorithm

We have an unsorted array, need to print the position of each element assuming that it gets sorted.

e.g.: we have an array.

arr[] = {3, 2, 6, 1, 4}
//index: 1  2  3  4  5  Index of elements 1-based

//Sorted {1, 2, 3, 4, 6}  List after sorting
//index:  4  2  1  5  3  Index of elements from original array

it should print

4 2 1 5 3

like image 590
ysyugeee Avatar asked Jun 11 '15 04:06

ysyugeee


People also ask

Which searching technique is best for unsorted array?

Binary Search. Sequential search is the best that we can do when trying to find a value in an unsorted array.

Which method has the best time complexity for searching an element in an unsorted array?

The most common algorithm to search an element in an unsorted array is using a linear search, checking element by element from the beginning to the end, this algorithm takes O(n) complexity.

What is the best case for finding an element in an unsorted list?

The best case of the unsorted array is O(n) while the worst case is also O(n).

Is an algorithm for locating the position of an element in a sorted list?

Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.


1 Answers

Sort the array {1, 2, 3, ..., N} in parallel with the given array. So in your example, {3, 2, 6, 4} would be sorted, with every swap affecting that array and the array {1, 2, 3, 4}. The final result would be {2, 3, 4, 6} for the first array and {2, 1, 4, 3} for the second; the latter array is the answer to your question.

In case that isn't clear, here's a longer example:

5 2 1 4 3
1 2 3 4 5

2 5 1 4 3
2 1 3 4 5

2 1 5 4 3
2 3 1 4 5

2 1 4 5 3
2 3 4 1 5

2 1 4 3 5
2 3 4 5 1

2 1 3 4 5
2 3 5 4 1

1 2 3 4 5
3 2 5 4 1

I used bubble sort :-) to sort the top row, and just swapped the bottom row in parallel with the top row. But the idea should work with any sorting method: just manipulate the bottom row in parallel with the operations (swaps or whatever) you are performing on the top row.

like image 94
Edward Doolittle Avatar answered Oct 11 '22 19:10

Edward Doolittle