Sorting and tracking index program

Hello guys i have been learning c++ for about 1 month. So my problem is that suppose i have array[6]={10,-1,3,54,2,12}

i want to fill new array with {1,4,2,0,5,3}

because -1 is the lowest and its index is 1
2 is the lowest and its index is 4
3 is the lowest and its index is 2
10 is the lowest and its index is 0
12is the lowest and its index is 5
54 is the lowest and its index is 3


i want to sort from lowest to highest but using the index value. Here is what i have but the output i get is {1,4,2,4,5,5}
1,4,2 is right but then its wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;

void swap(int& v1, int& v2);

int main()
{
	const int size = 6;
	
	int arry[6]={10,-1,3,54,2,12};
	int sortedArry[6];

	for(int startIndex = 0; startIndex < size; startIndex++)
	{
		int smallIndex = startIndex;
		for( int currentIndex = startIndex + 1; currentIndex < size; currentIndex++)
		{
			if(arry[currentIndex] < arry[smallIndex])
				smallIndex  = currentIndex; 
			//if(currentIndex + 1 == size)
			//	sortedArry[startIndex]=smallIndex;
		}
			sortedArry[startIndex] = smallIndex;
			swap(arry[startIndex],arry[smallIndex]);
			
	}

	for(int i = 0; i<size; i++)
		{
			cout << sortedArry[i]; 
		}
	
	

	system("pause");
}

void swap(int& v1, int& v2)
{
	int temp;
	temp = v1;
	v1=v2;
	v2=temp;
}
Last edited on
You'd better describe your algorithm in verbs rather than in code.

I suppose you should use arrays in some other way:

keep the array to be sorted
and array with indexes - it should be filled with values 0...N-1 at the start.

perform your algorithm to sort the first array. each time you are swapping elements in it - you also should swap elements at the same places in the second array.

Other variant is to store in the array not single numbers but structures of two numbers the value itself and its initial index - and sort by the first of them.

By the way, thanks - you have give me a good idea for one more problem to add to my site :)
Last edited on
Topic archived. No new replies allowed.