Currently working my way through the Jumping into C++ e-book, anyways the current chapter is on arrays, in said chapter we are given a way of sorting the variables in our array and then returning them in order from smallest to largest. The practice question asks us: Turn the code that we wrote for insertionSort into an insertionSort function that works for any sized array.
Now I thought this would be easy, but alas I was wrong, I cannot seem to figure out where to go with this one. The code below is what I have gotten so far, but my program is crashing so clearly it is not right... I thought that changing the for loop in int main from a hard coded i < 10 to a value that was input by the user would solve this practice problem, but I was wrong. Original: for ( int i = 0; i < 10; i++ ) ///// Mine: for ( int i = 0; i < arrayLength; i++ )
What am I not understanding here??? (code below)
Code:#include <cstdlib> #include <ctime> #include <iostream> using namespace std; int findSmallestRemainingElement (int array[], int size, int index); void swap (int array[], int first_index, int second_index); void sort (int array[], int size) { for ( int i = 0; i < size; i++ ) { int index = findSmallestRemainingElement( array, size, i ); swap( array, i, index ); } } int findSmallestRemainingElement (int array[], int size, int index) { int index_of_smallest_value = index; for (int i = index + 1; i < size; i++) { if ( array[ i ] < array[ index_of_smallest_value ] ) { index_of_smallest_value = i; } } return index_of_smallest_value; } void swap (int array[], int first_index, int second_index) { int temp = array[ first_index ]; array[ first_index ] = array[ second_index ]; array[ second_index ] = temp; } // small helper method to display the before and after arrays void displayArray (int array[], int size) { cout << "{"; for ( int i = 0; i < size; i++ ) { // you'll see this pattern a lot for nicely formatting // lists--check if we're past the first element, and // if so, append a comma if ( i != 0 ) { cout << ", "; } cout << array[ i ]; } cout << "}"; } int main () { int arrayLength; int array[ arrayLength ]; cout << "Please tell me how many numbers you would like in your array today: "; cin >> arrayLength; cout << "Thank you! \n"; srand( time( NULL ) ); for ( int i = 0; i < arrayLength; i++ ) { // keep the numbers small so they're easy to read array[ i ] = rand() % 100; } cout << "Original array: "; displayArray( array, arrayLength ); cout << '\n'; sort( array, arrayLength ); cout << "Sorted array: "; displayArray( array, arrayLength ); cout << '\n'; }



3Likes
LinkBack URL
About LinkBacks




