在 C++ 中按排序順序列印字串陣列,無需將一個字串複製到另一個字串


在本問題中,需要按排序順序列印字串陣列,而無需將一個字串複製到另一個字串。我們需要對字串陣列進行排序。在此過程中,程式設計師在排序時不能將一個字串複製到另一個字串。

讓我們來看一個例子來更好地理解這個概念。

示例 

Input : {“Delhi”, “Hyderabad”, “Indore”, “Mumbai”, “Banglore”}
Output : Banglore, Delhi, Hyderabad, Indore, Mumbai

說明 − 排序是按字典順序進行的。因此,以 B 開頭的 Bangalore 排在首位,以 M 開頭的 Mumbai 排在最後。

現在,讓我們嘗試找到解決我們問題的方案。

為了解決這個問題,我們可以建立一個數組來儲存這些字串的正確索引,因為實際上改變字串的位置需要進行復制。所以這是一種可能的解決方法。

我們將使用一個索引陣列,並使用排序技術對其進行排序,然後列印結果。這裡,我們將使用直接比較的選擇排序技術。

示例

現在讓我們建立一個程式來說明其工作原理 −

線上演示

#include <iostream>
using namespace std;
void sortedStringArray(string arr[], int n){
   int stringIndex[n];
   int i, j, min;
   for (i=0; i<n; i++)
   stringIndex[i] = i;
   for (i=0; i<n-1; i++){
      min = i;
      for (j=i+1; j<n; j++){
         if (arr[stringIndex[min]].compare(arr[stringIndex[j]]) > 0)
            min = j;
      }
      if (min != i){
         int temp = stringIndex[min];
         stringIndex[min] = stringIndex[i];
         stringIndex[i] = temp;
      }
   }
   for (i=0; i<n; i++)
      cout << arr[stringIndex[i]] << ", ";
}
int main(){
   string arr[] = {"Delhi", "Hyderabad", "Indore", "Mumbai", "Banglore"};
   int n = 5;
   sortedStringArray(arr, n);
   return 0;
}

輸出

Banglore, Delhi, Hyderabad, Indore, Mumbai,

更新於:2020年1月3日

443 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.