Well I tried to look for any posts on ranking arrays, but all I ever really got were stuff about Google's ranking system. Anyway, I have two arrays. One is arr[] which is the original array, and rank[] is the indexing array. So if I were to print arr[rank[0]], it would give me the smallest value of arr[]. Without further ado, here is the code!

#include <stdio.h>

int main(void)
{
  // Local Declarations
  int arr[5]={2,9,5,1,3};
  int rank[5]={0,1,2,3,4};
  int i; int j;
  int smallest;
  int temp;

  // Statements

  for(i=0;i<4;i++)
    {
      smallest = i;
      for(j=i+1;j<=4;j++)
	if(arr[rank[smallest]] > arr[rank[j]])
          smallest = j;

      temp = rank[i];
      rank[i] = smallest;
      rank[smallest] = temp;
      printf("\n");
      for(i=0;i<5;i++)
        printf("%3d", rank[i]);
      printf("\n");
    }
   for(i=0;i<5;i++)
    printf("%3d", arr[i]);
  printf("\n");

  return 0;
} // main

/* Execution Results

  3  1  2  0  4
  2  9  5  1  3
*/

For some reason, the for loop for the ranking sort just goes through only once. Otherwise it would print the ranking array 3 more times I believe. Any help would be greatly appreciated. Thanks in advance!

Using more { } to denote exactly which bits of code belong to which block would certainly help clarify the problem.

very simple: you are using ' i ' in two nested loops and every time you enter a loop i becomes 0 (lines 14 and 25)

Okay, I fixed line 25 to loop with k instead of i. Now I'm getting 3 more arrays printed out, although not in the correct order.

3 1 2 0 4 //this one is correct

3 3 2 1 4 //but not this one... the second 3 should be a 0 instead...

3 3 4 1 2

3 3 4 4 1
2 9 5 1 3 //original array

I have no idea what your program is supposed to do, so maybe you could clear this up?

The array rank[] is supposed to be an indexing array that sorts the arr[] from low to high. For example, arr[rank[0]] would give me the lowest value, which in this case would be 1. arr[rank[1]] would give me the second lowest number which is 2.

Hmm, sounds a bit strange to me. How about using a simple bubblesort on the original array? That way arr[0] would be smallest and arr[4] will be biggest. No need for an extra array right?

Okay, I got it. The reason why was because "smallest" in line 22 wasn't an array address. When I changed it to rank[smallest] it worked just fine. Thank you for your help guys, I really appreciate it! Now I can go to sleep...

Well that sort of defeats the purpose of a ranking sort. It's used so that the original array's order is not tampered with so it could still be used as a reference for something. Thanks for your input though.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.