使用 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