我希望第69行的displayArray每次迭代时都能工作,以显示插入排序的变化。我还没有能够让它工作,并且已经旋转了一下我的车轮。请帮忙/解释。先感谢您。 这就是我的输出应该是这样的:
预期输出:
Enter up to 20 nonnegative whole numbers. Mark the end of the list with a negative number. 3 7 4 9 5 2 6 1 -1 3 7 4 9 5 2 6 1 3 4 7 9 5 2 6 1 3 4 7 9 5 2 6 1 3 4 5 7 9 2 6 1 2 3 4 5 7 9 6 1 2 3 4 5 6 7 9 1 1 2 3 4 5 6 7 9
按排序顺序,数字为:
1 2 3 4 5 6 7 9
代码:
#include <iostream>
using namespace std;
const int MAX_SIZE = 20;
// Fills the array a[] with data from the user for a[0] through a[numberUsed -1].
// Since the user will not necessarily use up all the allocated entries in the array,
// the function will set the actual number of entries used in the "numberUsed"
// reference variable.
void fillArray(int a[], int arraySize, int& numberUsed);
// Sorts the array a[] such that a[0] <= a[1] <= ... <= a[numberUsed - 1].
void insert_sort(int a[], int numberUsed);
// Interchanges the values of v1 and v2.
void swapValues(int& v1, int& v2);
// Displays the contents of the array
void displayArray(const int a[], int numberUsed);
int main( )
{
cout << "This program sorts numbers from lowest to highest.\n";
int sampleArray[MAX_SIZE] = {0};
int numberUsed = 0;
fillArray(sampleArray, MAX_SIZE, numberUsed);
insert_sort(sampleArray, numberUsed);
cout << "In sorted order the numbers are:\n";
displayArray(sampleArray, numberUsed);
return 0;
}
void fillArray(int a[], int arraySize, int& numberUsed)
{
cout << "Enter up to " << arraySize << " nonnegative whole numbers.\n"
<< "Mark the end of the list with a negative number.\n";
int next = 0;
int index = 0;
cin >> next;
while ((next >= 0) && (index < arraySize))
{
a[index] = next;
index++;
cin >> next;
}
numberUsed = index;
}
void insertion_sort (int a[], int numberUsed){
int j, temp;
for (int i = 0; i < numberUsed; i++){
j = i;
while (j > 0 && a[j] < a[j-1]){
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
j--;
}
displayArray(a,numberUsed);
}
}
void swapValues(int& v1, int& v2)
{
int temp;
temp = v1;
v1 = v2;
v2 = temp;
}
void displayArray(const int a[], int numberUsed)
{
for (int index = 0; index < numberUsed; index++)
{
cout << a[index] << " ";
}
cout << endl;
}