首页 > 解决方案 > 反转后不返回最后一个元素

问题描述

所以我必须编写一个程序,首先放入一个字符串数组,然后插入排序,输出,然后反转数组并再次输出。我只是有一个小问题。最后一个元素(反转后,最初是第一个元素)不打印?我打赌这很容易解决,但是有人知道如何解决吗?任何帮助表示赞赏!谢谢!

#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;

 }

标签: c++

解决方案


一个大小数组的s索引从0s-1。在你的 reverse 函数中,写end = numWords - 1;而不是end = numWords.


推荐阅读