AHunt
AHunt

Reputation: 67

How to print out an array using a while loop and and a variable representing the size of the array?

I keep on getting the same numbers 166 and 74. I am trying to get 74 166 250 273 441 545 659 710 808 879 924 931. I really have no idea where to find this bug. I do know that main function is correct but I am not sure on where to find the bug that is just giving me 166 and 74.

#include <stdio.h>

// Swap the values pointed to by a and b.
void swap( int *a, int *b )
{
  int temp = *a;

  *a = *b;

  *b = temp;
}

// Return a pointer to the element of the given array with the smallest value.
int *findSmallest( int *list, int len )
{
  int *smallest = list;
  for ( int i = 1; i < len; i++ ) {

       if(*smallest > *(list + i)) {

       *smallest = *(list + i);

       }

  }

  return smallest;
}

// Print the contents of the given list.
void printList( int *list, int len )
{
  while ( len ) {

    len--;

    printf("%d ", *(list + --len));


  }

  printf( "\n" );
}

int main()
{
  // A list of random-ish values.
  int list[] = { 808, 250, 74, 659, 931, 273, 545, 879, 924, 710, 441, 166 };
  int len = sizeof( list ) / sizeof( list[ 0 ] );

  // For each index, find the smallest item from the remaining
  // (unsorted) portion of the list.
  for ( int i = 0; i < len; i++ ) {

    int *p = findSmallest( list + i, len - i );

    // Swap the smallest item into the first position in the unsorted part of the
    // list.
    swap( list + i, p );
  }

  printList( list, len );
}
}

Upvotes: 1

Views: 756

Answers (2)

user3629249
user3629249

Reputation: 16540

this code:

int *findSmallest( int *list, int len )
{
    int *smallest = list;
    for ( int i = 1; i < len; i++ ) {

       if(*smallest > *(list + i)) {

           *smallest = *(list + i);

       }

    }

should be calling swap() so the original value in position list[0] is not overlayed in the statement: *smallest = *(list + i);

Upvotes: 0

Pedro LM
Pedro LM

Reputation: 750

len--;
printf("%d ", *(list + --len));

You're decrementing len twice.


...but the main problem is this line in findSmallest:

*smallest = *(list + i);

Here smallest points to an element in the list, and you're overwriting that element. Instead, you should be changing smallest itself so it points to another element:

smallest = (list + i);

With these two fixes, here's the output:

931 924 879 808 710 659 545 441 273 250 166 74

The list, correctly sorted and printed back-to-front.

Upvotes: 3

Related Questions