使用 C++ 中的選擇排序對字串陣列進行排序
選擇排序演算法透過多次從未排序的部分中找到最小元素並將其放到前面來對陣列排序。在確定排序的每次迭代中,選擇未排序子陣列中的最小元素並將其移動到已排序的子陣列中。
示例
#include <iostream>
#include <string.h>
using namespace std;
#define MAX_LEN 50
void selectionSort(char arr[][50], int n){
int i, j, mIndex;
// Move boundary of unsorted subarray one by one
char minStr[50];
for (i = 0; i < n-1; i++){
// Determine minimum element in unsorted array
int mIndex = i;
strcpy(minStr, arr[i]);
for (j = i + 1; j < n; j++){
// check whether the min is greater than arr[j]
if (strcmp(minStr, arr[j]) > 0){
// Make arr[j] as minStr and update min_idx
strcpy(minStr, arr[j]);
mIndex = j;
}
}
// Swap the minimum with the first element
if (mIndex != i){
char temp[50];
strcpy(temp, arr[i]); //swap item[pos] and item[i]
strcpy(arr[i], arr[mIndex]);
strcpy(arr[mIndex], temp);
}
}
}
int main(){
char arr[][50] = {"Tom", "Boyaka", "Matt" ,"Luke"};
int n = sizeof(arr)/sizeof(arr[0]);
int i;
cout<<"Given String is:: Tom, Boyaka, Matt, Luke\n";
selectionSort(arr, n);
cout << "\nSelection Sorted is::\n";
for (i = 0; i < n; i++)
cout << i << ": " << arr[i] << endl;
return 0;
}此 C++ 程式首先選擇陣列中的最小元素,並用叢集中的主要元素進行交換。接下來,將叢集中的第二小元素與後續元素交換等。透過這種方式,對於每次傳遞,選擇陣列中的最小元素並將其放置在其合法的位置,直到整個叢集被排序。最後,區段排序方法按照如下方式對給定的字串進行升序排序;
輸出
Given string is:: Tom, Boyaka, Matt, Luke Selection Sorted:: Boyaka Luke Matt Tom
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP