15,614,257 members
See more:
Hi,

I have a one-d Array named zz containing {5,3,8,1,9,6}. Current order of indices of the elements is : 0,1,2,3,4,5.

Now I want to sort the array z in ascending order in such a way that its corresponding indices also sort according to its respective elements.

Ex: Elts in Ascending order : 1,3,5,6,8,9

and Respective indices will be : 3,1,0,5,2,4.

Another Ex: What "Additions" should i make to the following code, if the Array Element repeats ?? Epected Oreder of Indices : 1,0,4,3,2

```int[] A = new int[6] { 3, 2, 8, 5, 3 };  //{ 5, 3, 8, 1, 9, 6 };
int[] B = new int[6];
int[] index = new int[6];
int flag = 0;
Console.WriteLine("Array A:");
for (int i = 0; i < A.Length; i++)
Console.Write(A[i]);
Console.WriteLine();
Array.Copy(A, B, A.Length);
Console.WriteLine("Array B:");
for (int i = 0; i < B.Length; i++)
Console.Write(B[i]);
Console.WriteLine();
Array.Sort(A);
Console.WriteLine("Sorted Array B:");
for (int i = 0; i < A.Length; i++)
Console.Write(A[i]);
Console.WriteLine();

for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
flag = 0;
for (int k = 0; k < 6; k++)
{
if (A[j + i] == B[k])
{
index[i] = k;
flag = 1;
break;
}
}
if (flag == 1)
break;
}
}

Console.WriteLine("Index Array index:");
for (int i = 0; i < index.Length; i++)
Console.Write(index[i]);

Is there any ready made function available ? Hope the question is clear..Kindly provide the solution on urgent basis.

Posted
Updated 28-Oct-10 21:14pm
v3
Member 4264918 29-Oct-10 3:04am
i am also facing the same problem please provide solution

## Solution 1

You want to turn your array into a list of type int, sort that and turn the sorted list back into an array.

```var intList = new List<int>(A);
intList.Sort();

var sortedArrayOfIntegers = intList.ToArray();
</int>```

hope this helps.

## Solution 2

Try this.

C#
```int[] A = { 3, 2, 8, 5, 3 };  //{ 5, 3, 8, 1, 9, 6 };
int[] index = new int[A.Length];
int[] result = new int[A.Length];
Array.Copy(A, result, A.Length);
for (int i = 0; i < A.Length; i++) index[i] = i;
Console.WriteLine("Input Array:");
for (int i = 0; i < A.Length; i++)
Console.Write(A[i]);
Console.WriteLine();
Console.WriteLine("Original Index Array:");
for (int i = 0; i < index.Length; i++)
Console.Write(index[i]);
Console.WriteLine();
int lastIndex = 0;
int tempValue = 0;
for (int i = 0; i < A.Length; i++)
{
for (int j = i + 1; j < A.Length; j++)
{
if (result[i] > result[j])
{
tempValue = result[i];
result[i] = result[j];
result[j] = tempValue;
lastIndex = index[i];
index[i] = index[j];
index[j] = lastIndex;
}
}
}

Console.WriteLine("Result Array:");
for (int i = 0; i < result.Length; i++)
Console.Write(result[i]);
Console.WriteLine();
Console.WriteLine("Sorted Index Array:");
for (int i = 0; i < index.Length; i++)
Console.Write(index[i]);

Dalek Dave 29-Oct-10 4:41am
shwetavc30 29-Oct-10 4:54am
Hey thanks a lot.. It worked great :)
qontary 29-Oct-10 5:46am