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;
}
|