反转后不返回最后一个元素

时间:2018-09-26 20:10:17

标签: c++

因此,我必须编写一个程序,在该程序中,我首先放入一个字符串数组,然后插入对它进行排序,将其输出,然后反转该数组并再次输出。我只是有一个小问题。最后一个元素(反转后原为第一个元素)不打印?我敢打赌这是一个简单的解决方法,但是有人知道如何解决吗?任何帮助表示赞赏!谢谢!

#include <iostream>
#include <string>
using namespace std;

string insertionSort(string[], int);
string reverseSort(string[], int);

string insertionSort(string words[], int numWords) {
int i = 0;
int j = 0;
string temp = "";

for (i = 0; i < numWords; i++) {
  j = i;
  while (j > 0 && words[j] < words[j - 1]) {
     temp = words[j];
     words[j] = words[j - 1];
     words[j - 1] = temp;
     j--;
    }
}
return temp;
}

string insertionSortRev(string words[], int numWords) { //reverse array
int start = 0;
int end = numWords;
string temp = "";

while (start < end) {
  string temp = words[start];
  words[start] = words[end];
  words[end] = temp;
  start++;
  end--;
  }
  return temp;
  }


int main() {
string words[] = {"", "", "", "", "", "", "", "", "", ""};
int numWords = 0;

cin >> numWords;

for (int i = 0; i < numWords; i++) {
cin >> words[i];
}

cout << "UNSORTED: ";
for (int i = 0; i < numWords; i++) {
cout << words[i] << " ";
}
cout << endl;

insertionSort(words, numWords);

 cout << "SORTED: ";
 for(int z = 0; z < numWords; z++) {
    cout << words[z] << " ";
 }
 cout << endl;

 insertionSortRev(words, numWords);

 cout << "REVERSED: ";
 for (int k = 0; k < numWords; k++) {
 cout << words[k] << " ";
 }
 cout << endl;

 return 0;

 }

1 个答案:

答案 0 :(得分:2)

将大小为s的数组从0索引为s-1。在您的反向函数中,写end = numWords - 1;而不是end = numWords