Hello. I am learning C++, and I am a little stuck. Right now, I'm working on pointers. The problem I'm working on requires sorting an array of structures, using pointers instead of array indices, using a selection sort. My code is not working, and I can't quite figure out why. I am able to do the problem using a bubble sort, however.

I am pretty new to pointers and sorting algorithms in general, so it's possible I am just missing something really simple. Here is the code:

void selection_sort(Student *ptr, int size)
{
  int start,
    min_index,
    min_value;
  Student temp;

  for (start = 0; start < (size - 1); start++) {
    min_index = start;
    min_value = ptr[start].score;
    for (int index = start+1; index < size; index++) {
      if ( ptr[start].score < min_value) {
	min_value = ptr[index].score;
	min_index = index;
      }
    }
    // the following lines are where I think the problem lies,
    // but I can't figure out the solution
    temp = *(ptr+min_index);
    *(ptr+min_index) = *(ptr+start);
    *(ptr+start) = temp;
  }
}

Right now, the output of this code after being passed to main is just an unsorted list, with the structures in the same order as when they were passed. It's not a scope issue, as I tried outputting the results within this function and got the same result.

I am still trying to wrap my head around the proper implementation of pointers (and, honestly, the selection sort as well), so any help would be greatly appreciated. Thank you.

Haha...I had that all messed up. I had to walk through it on paper, and then it became obvious. For anyone wondering in the future, I did not properly initialize the temp variable, and I assigned some values in the wrong place. Here is the correct code:

void selection_sort(Student *ptr, int size)
{
  int start,
    minIndex;
  Student temp;   
  double minValue;
  
  for (start = 0; start < (size-1); start++) {
    minIndex = start;
    minValue = ptr[start].score;
    temp = ptr[start]; // note temp initialized here
    for (int index = start+1; index < size; index++) {
      if (ptr[index].score < minValue) { 
	temp = ptr[index]; // new value copied into temp
	minIndex = index;
      }
    }
    ptr[minIndex] = ptr[start];
    ptr[start] = temp;  // value copied back -- these three comments specify crucial 
  }                     // aspects that made it work
}
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.